[GTK] WebDriver: implement AutomationSessionClient::didDisconnectFromRemote
[WebKit-https.git] / Source / WebDriver / glib / SessionHostGlib.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 INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "SessionHost.h"
28
29 #include "WebDriverService.h"
30 #include <gio/gio.h>
31 #include <wtf/RunLoop.h>
32 #include <wtf/UUID.h>
33 #include <wtf/glib/GUniquePtr.h>
34
35 #define REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "org.webkit.RemoteInspectorClient"
36 #define REMOTE_INSPECTOR_CLIENT_OBJECT_PATH "/org/webkit/RemoteInspectorClient"
37 #define INSPECTOR_DBUS_INTERFACE "org.webkit.Inspector"
38 #define INSPECTOR_DBUS_OBJECT_PATH "/org/webkit/Inspector"
39
40 namespace WebDriver {
41
42 SessionHost::~SessionHost()
43 {
44     g_cancellable_cancel(m_cancellable.get());
45     if (m_browser)
46         g_subprocess_force_exit(m_browser.get());
47 }
48
49 static const char introspectionXML[] =
50     "<node>"
51     "  <interface name='" REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "'>"
52     "    <method name='SetTargetList'>"
53     "      <arg type='t' name='connectionID' direction='in'/>"
54     "      <arg type='a(tsssb)' name='list' direction='in'/>"
55     "    </method>"
56     "    <method name='SendMessageToFrontend'>"
57     "      <arg type='t' name='connectionID' direction='in'/>"
58     "      <arg type='t' name='target' direction='in'/>"
59     "      <arg type='s' name='message' direction='in'/>"
60     "    </method>"
61     "  </interface>"
62     "</node>";
63
64 const GDBusInterfaceVTable SessionHost::s_interfaceVTable = {
65     // method_call
66     [](GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) {
67         auto* sessionHost = static_cast<SessionHost*>(userData);
68         if (!g_strcmp0(methodName, "SetTargetList")) {
69             guint64 connectionID;
70             GUniqueOutPtr<GVariantIter> iter;
71             g_variant_get(parameters, "(ta(tsssb))", &connectionID, &iter.outPtr());
72             size_t targetCount = g_variant_iter_n_children(iter.get());
73             Vector<SessionHost::Target> targetList;
74             targetList.reserveInitialCapacity(targetCount);
75             guint64 targetID;
76             const char* type;
77             const char* name;
78             const char* dummy;
79             gboolean isPaired;
80             while (g_variant_iter_loop(iter.get(), "(t&s&s&sb)", &targetID, &type, &name, &dummy, &isPaired)) {
81                 if (!g_strcmp0(type, "Automation"))
82                     targetList.uncheckedAppend({ targetID, name, static_cast<bool>(isPaired) });
83             }
84             sessionHost->setTargetList(connectionID, WTFMove(targetList));
85             g_dbus_method_invocation_return_value(invocation, nullptr);
86         } else if (!g_strcmp0(methodName, "SendMessageToFrontend")) {
87             guint64 connectionID, targetID;
88             const char* message;
89             g_variant_get(parameters, "(tt&s)", &connectionID, &targetID, &message);
90             sessionHost->sendMessageToFrontend(connectionID, targetID, message);
91             g_dbus_method_invocation_return_value(invocation, nullptr);
92         }
93     },
94     // get_property
95     nullptr,
96     // set_property
97     nullptr,
98     // padding
99     { 0 }
100 };
101
102 void SessionHost::connectToBrowser(Function<void (std::optional<String> error)>&& completionHandler)
103 {
104     launchBrowser(WTFMove(completionHandler));
105 }
106
107 bool SessionHost::isConnected() const
108 {
109     return !!m_browser;
110 }
111
112 struct ConnectToBrowserAsyncData {
113     ConnectToBrowserAsyncData(SessionHost* sessionHost, GUniquePtr<char>&& dbusAddress, GCancellable* cancellable, Function<void (std::optional<String> error)>&& completionHandler)
114         : sessionHost(sessionHost)
115         , dbusAddress(WTFMove(dbusAddress))
116         , cancellable(cancellable)
117         , completionHandler(WTFMove(completionHandler))
118     {
119     }
120
121     SessionHost* sessionHost;
122     GUniquePtr<char> dbusAddress;
123     GRefPtr<GCancellable> cancellable;
124     Function<void (std::optional<String> error)> completionHandler;
125 };
126
127 static guint16 freePort()
128 {
129     GRefPtr<GSocket> socket = adoptGRef(g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, nullptr));
130     GRefPtr<GInetAddress> loopbackAdress = adoptGRef(g_inet_address_new_loopback(G_SOCKET_FAMILY_IPV4));
131     GRefPtr<GSocketAddress> address = adoptGRef(g_inet_socket_address_new(loopbackAdress.get(), 0));
132     g_socket_bind(socket.get(), address.get(), FALSE, nullptr);
133     g_socket_listen(socket.get(), nullptr);
134     address = adoptGRef(g_socket_get_local_address(socket.get(), nullptr));
135     g_socket_close(socket.get(), nullptr);
136     return g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(address.get()));
137 }
138
139 void SessionHost::launchBrowser(Function<void (std::optional<String> error)>&& completionHandler)
140 {
141     m_cancellable = adoptGRef(g_cancellable_new());
142     GRefPtr<GSubprocessLauncher> launcher = adoptGRef(g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_NONE));
143     guint16 port = freePort();
144     GUniquePtr<char> inspectorAddress(g_strdup_printf("127.0.0.1:%u", port));
145     g_subprocess_launcher_setenv(launcher.get(), "WEBKIT_INSPECTOR_SERVER", inspectorAddress.get(), TRUE);
146 #if PLATFORM(GTK)
147     g_subprocess_launcher_setenv(launcher.get(), "GTK_OVERLAY_SCROLLING", m_capabilities.useOverlayScrollbars.value() ? "1" : "0", TRUE);
148 #endif
149
150     const auto& browserArguments = m_capabilities.browserArguments.value();
151     GUniquePtr<char*> args(g_new0(char*, browserArguments.size() + 2));
152     args.get()[0] = g_strdup(m_capabilities.browserBinary.value().utf8().data());
153     for (unsigned i = 0; i < browserArguments.size(); ++i)
154         args.get()[i + 1] = g_strdup(browserArguments[i].utf8().data());
155
156     GUniqueOutPtr<GError> error;
157     m_browser = adoptGRef(g_subprocess_launcher_spawnv(launcher.get(), args.get(), &error.outPtr()));
158     if (error) {
159         completionHandler(String::fromUTF8(error->message));
160         return;
161     }
162
163     g_subprocess_wait_async(m_browser.get(), m_cancellable.get(), [](GObject* browser, GAsyncResult* result, gpointer userData) {
164         GUniqueOutPtr<GError> error;
165         g_subprocess_wait_finish(G_SUBPROCESS(browser), result, &error.outPtr());
166         if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
167             return;
168         auto* sessionHost = static_cast<SessionHost*>(userData);
169         sessionHost->m_browser = nullptr;
170     }, this);
171
172     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", "127.0.0.1", port));
173     connectToBrowser(std::make_unique<ConnectToBrowserAsyncData>(this, WTFMove(dbusAddress), m_cancellable.get(), WTFMove(completionHandler)));
174 }
175
176 void SessionHost::connectToBrowser(std::unique_ptr<ConnectToBrowserAsyncData>&& data)
177 {
178     if (!m_browser)
179         return;
180
181     RunLoop::main().dispatchAfter(100_ms, [connectToBrowserData = WTFMove(data)]() mutable {
182         auto* data = connectToBrowserData.release();
183         if (g_cancellable_is_cancelled(data->cancellable.get()))
184             return;
185
186         g_dbus_connection_new_for_address(data->dbusAddress.get(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, data->cancellable.get(),
187             [](GObject*, GAsyncResult* result, gpointer userData) {
188                 auto data = std::unique_ptr<ConnectToBrowserAsyncData>(static_cast<ConnectToBrowserAsyncData*>(userData));
189                 GUniqueOutPtr<GError> error;
190                 GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr()));
191                 if (!connection) {
192                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
193                         return;
194
195                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED)) {
196                         data->sessionHost->connectToBrowser(WTFMove(data));
197                         return;
198                     }
199
200                     data->completionHandler(String::fromUTF8(error->message));
201                     return;
202                 }
203                 data->sessionHost->setupConnection(WTFMove(connection));
204                 data->completionHandler(std::nullopt);
205         }, data);
206     });
207 }
208
209 void SessionHost::dbusConnectionClosedCallback(SessionHost* sessionHost)
210 {
211     sessionHost->m_browser = nullptr;
212     sessionHost->inspectorDisconnected();
213 }
214
215 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
216 {
217     GUniqueOutPtr<GError> error;
218     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
219     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
220         WTFLogAlways("RemoteInspectorServer failed to send DBus message: %s", error->message);
221 }
222
223 void SessionHost::setupConnection(GRefPtr<GDBusConnection>&& connection)
224 {
225     ASSERT(!m_dbusConnection);
226     ASSERT(connection);
227     m_dbusConnection = WTFMove(connection);
228
229     g_signal_connect_swapped(m_dbusConnection.get(), "closed", G_CALLBACK(dbusConnectionClosedCallback), this);
230
231     static GDBusNodeInfo* introspectionData = nullptr;
232     if (!introspectionData)
233         introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
234
235     g_dbus_connection_register_object(m_dbusConnection.get(), REMOTE_INSPECTOR_CLIENT_OBJECT_PATH, introspectionData->interfaces[0], &s_interfaceVTable, this, nullptr, nullptr);
236 }
237
238 static bool matchBrowserOptions(const String& browserName, const String& browserVersion, const Capabilities& capabilities)
239 {
240     if (capabilities.browserName && capabilities.browserName.value() != browserName)
241         return false;
242
243     if (capabilities.browserVersion && !WebDriverService::platformCompareBrowserVersions(capabilities.browserVersion.value(), browserVersion))
244         return false;
245
246     return true;
247 }
248
249 bool SessionHost::matchCapabilities(GVariant* capabilities)
250 {
251     const char* name;
252     const char* version;
253     g_variant_get(capabilities, "(&s&s)", &name, &version);
254
255     auto browserName = String::fromUTF8(name);
256     auto browserVersion = String::fromUTF8(version);
257     bool didMatch = matchBrowserOptions(browserName, browserVersion, m_capabilities);
258     m_capabilities.browserName = browserName;
259     m_capabilities.browserVersion = browserVersion;
260
261     return didMatch;
262 }
263
264 void SessionHost::startAutomationSession(Function<void (bool, std::optional<String>)>&& completionHandler)
265 {
266     ASSERT(m_dbusConnection);
267     ASSERT(!m_startSessionCompletionHandler);
268     m_startSessionCompletionHandler = WTFMove(completionHandler);
269     m_sessionID = createCanonicalUUIDString();
270     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
271         INSPECTOR_DBUS_OBJECT_PATH,
272         INSPECTOR_DBUS_INTERFACE,
273         "StartAutomationSession",
274         g_variant_new("(s)", m_sessionID.utf8().data()),
275         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
276         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
277             GUniqueOutPtr<GError> error;
278             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
279             if (!resultVariant && g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
280                 return;
281
282             auto sessionHost = static_cast<SessionHost*>(userData);
283             if (!resultVariant) {
284                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
285                 completionHandler(false, String("Failed to start automation session"));
286                 return;
287             }
288
289             if (!sessionHost->matchCapabilities(resultVariant.get())) {
290                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
291                 completionHandler(false, std::nullopt);
292                 return;
293             }
294         }, this
295     );
296 }
297
298 void SessionHost::setTargetList(uint64_t connectionID, Vector<Target>&& targetList)
299 {
300     // The server notifies all its clients when connection is lost by sending an empty target list.
301     // We only care about automation connection.
302     if (m_connectionID && m_connectionID != connectionID)
303         return;
304
305     ASSERT(targetList.size() <= 1);
306     if (targetList.isEmpty()) {
307         m_target = Target();
308         m_connectionID = 0;
309         if (m_dbusConnection)
310             g_dbus_connection_close(m_dbusConnection.get(), nullptr, nullptr, nullptr);
311         return;
312     }
313
314     m_target = targetList[0];
315     if (m_connectionID) {
316         ASSERT(m_connectionID == connectionID);
317         return;
318     }
319
320     if (!m_startSessionCompletionHandler) {
321         // Session creation was already rejected.
322         return;
323     }
324
325     m_connectionID = connectionID;
326     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
327         INSPECTOR_DBUS_OBJECT_PATH,
328         INSPECTOR_DBUS_INTERFACE,
329         "Setup",
330         g_variant_new("(tt)", m_connectionID, m_target.id),
331         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
332         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
333
334     auto startSessionCompletionHandler = std::exchange(m_startSessionCompletionHandler, nullptr);
335     startSessionCompletionHandler(true, std::nullopt);
336 }
337
338 void SessionHost::sendMessageToFrontend(uint64_t connectionID, uint64_t targetID, const char* message)
339 {
340     if (connectionID != m_connectionID || targetID != m_target.id)
341         return;
342     dispatchMessage(String::fromUTF8(message));
343 }
344
345 struct MessageContext {
346     long messageID;
347     SessionHost* host;
348 };
349
350 void SessionHost::sendMessageToBackend(long messageID, const String& message)
351 {
352     ASSERT(m_dbusConnection);
353     ASSERT(m_connectionID);
354     ASSERT(m_target.id);
355
356     auto messageContext = std::make_unique<MessageContext>(MessageContext { messageID, this });
357     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
358         INSPECTOR_DBUS_OBJECT_PATH,
359         INSPECTOR_DBUS_INTERFACE,
360         "SendMessageToBackend",
361         g_variant_new("(tts)", m_connectionID, m_target.id, message.utf8().data()),
362         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
363         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
364             auto messageContext = std::unique_ptr<MessageContext>(static_cast<MessageContext*>(userData));
365             GUniqueOutPtr<GError> error;
366             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
367             if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
368                 auto responseHandler = messageContext->host->m_commandRequests.take(messageContext->messageID);
369                 if (responseHandler) {
370                     auto errorObject = JSON::Object::create();
371                     errorObject->setInteger(ASCIILiteral("code"), -32603);
372                     errorObject->setString(ASCIILiteral("message"), String::fromUTF8(error->message));
373                     responseHandler({ WTFMove(errorObject), true });
374                 }
375             }
376         }, messageContext.release());
377 }
378
379 } // namespace WebDriver