[GTK] WebDriver: test imported/w3c/webdriver/tests/sessions/new_session/response...
[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/glib/GUniquePtr.h>
33
34 #define REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "org.webkit.RemoteInspectorClient"
35 #define REMOTE_INSPECTOR_CLIENT_OBJECT_PATH "/org/webkit/RemoteInspectorClient"
36 #define INSPECTOR_DBUS_INTERFACE "org.webkit.Inspector"
37 #define INSPECTOR_DBUS_OBJECT_PATH "/org/webkit/Inspector"
38
39 namespace WebDriver {
40
41 SessionHost::~SessionHost()
42 {
43     g_cancellable_cancel(m_cancellable.get());
44     if (m_browser)
45         g_subprocess_force_exit(m_browser.get());
46 }
47
48 static const char introspectionXML[] =
49     "<node>"
50     "  <interface name='" REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "'>"
51     "    <method name='SetTargetList'>"
52     "      <arg type='t' name='connectionID' direction='in'/>"
53     "      <arg type='a(tsssb)' name='list' direction='in'/>"
54     "    </method>"
55     "    <method name='SendMessageToFrontend'>"
56     "      <arg type='t' name='connectionID' direction='in'/>"
57     "      <arg type='t' name='target' direction='in'/>"
58     "      <arg type='s' name='message' direction='in'/>"
59     "    </method>"
60     "  </interface>"
61     "</node>";
62
63 const GDBusInterfaceVTable SessionHost::s_interfaceVTable = {
64     // method_call
65     [](GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) {
66         auto* sessionHost = static_cast<SessionHost*>(userData);
67         if (!g_strcmp0(methodName, "SetTargetList")) {
68             guint64 connectionID;
69             GUniqueOutPtr<GVariantIter> iter;
70             g_variant_get(parameters, "(ta(tsssb))", &connectionID, &iter.outPtr());
71             size_t targetCount = g_variant_iter_n_children(iter.get());
72             Vector<SessionHost::Target> targetList;
73             targetList.reserveInitialCapacity(targetCount);
74             guint64 targetID;
75             const char* type;
76             const char* name;
77             const char* dummy;
78             gboolean isPaired;
79             while (g_variant_iter_loop(iter.get(), "(t&s&s&sb)", &targetID, &type, &name, &dummy, &isPaired)) {
80                 if (!g_strcmp0(type, "Automation"))
81                     targetList.uncheckedAppend({ targetID, name, static_cast<bool>(isPaired) });
82             }
83             sessionHost->setTargetList(connectionID, WTFMove(targetList));
84             g_dbus_method_invocation_return_value(invocation, nullptr);
85         } else if (!g_strcmp0(methodName, "SendMessageToFrontend")) {
86             guint64 connectionID, targetID;
87             const char* message;
88             g_variant_get(parameters, "(tt&s)", &connectionID, &targetID, &message);
89             sessionHost->sendMessageToFrontend(connectionID, targetID, message);
90             g_dbus_method_invocation_return_value(invocation, nullptr);
91         }
92     },
93     // get_property
94     nullptr,
95     // set_property
96     nullptr,
97     // padding
98     { 0 }
99 };
100
101 void SessionHost::connectToBrowser(Function<void (std::optional<String> error)>&& completionHandler)
102 {
103     launchBrowser(WTFMove(completionHandler));
104 }
105
106 bool SessionHost::isConnected() const
107 {
108     return !!m_browser;
109 }
110
111 struct ConnectToBrowserAsyncData {
112     ConnectToBrowserAsyncData(SessionHost* sessionHost, GUniquePtr<char>&& dbusAddress, GCancellable* cancellable, Function<void (std::optional<String> error)>&& completionHandler)
113         : sessionHost(sessionHost)
114         , dbusAddress(WTFMove(dbusAddress))
115         , cancellable(cancellable)
116         , completionHandler(WTFMove(completionHandler))
117     {
118     }
119
120     SessionHost* sessionHost;
121     GUniquePtr<char> dbusAddress;
122     GRefPtr<GCancellable> cancellable;
123     Function<void (std::optional<String> error)> completionHandler;
124 };
125
126 static guint16 freePort()
127 {
128     GRefPtr<GSocket> socket = adoptGRef(g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, nullptr));
129     GRefPtr<GInetAddress> loopbackAdress = adoptGRef(g_inet_address_new_loopback(G_SOCKET_FAMILY_IPV4));
130     GRefPtr<GSocketAddress> address = adoptGRef(g_inet_socket_address_new(loopbackAdress.get(), 0));
131     g_socket_bind(socket.get(), address.get(), FALSE, nullptr);
132     g_socket_listen(socket.get(), nullptr);
133     address = adoptGRef(g_socket_get_local_address(socket.get(), nullptr));
134     g_socket_close(socket.get(), nullptr);
135     return g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(address.get()));
136 }
137
138 void SessionHost::launchBrowser(Function<void (std::optional<String> error)>&& completionHandler)
139 {
140     m_cancellable = adoptGRef(g_cancellable_new());
141     GRefPtr<GSubprocessLauncher> launcher = adoptGRef(g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_NONE));
142     guint16 port = freePort();
143     GUniquePtr<char> inspectorAddress(g_strdup_printf("127.0.0.1:%u", port));
144     g_subprocess_launcher_setenv(launcher.get(), "WEBKIT_INSPECTOR_SERVER", inspectorAddress.get(), TRUE);
145 #if PLATFORM(GTK)
146     g_subprocess_launcher_setenv(launcher.get(), "GTK_OVERLAY_SCROLLING", m_capabilities.useOverlayScrollbars.value() ? "1" : "0", TRUE);
147 #endif
148
149     const auto& browserArguments = m_capabilities.browserArguments.value();
150     GUniquePtr<char*> args(g_new0(char*, browserArguments.size() + 2));
151     args.get()[0] = g_strdup(m_capabilities.browserBinary.value().utf8().data());
152     for (unsigned i = 0; i < browserArguments.size(); ++i)
153         args.get()[i + 1] = g_strdup(browserArguments[i].utf8().data());
154
155     GUniqueOutPtr<GError> error;
156     m_browser = adoptGRef(g_subprocess_launcher_spawnv(launcher.get(), args.get(), &error.outPtr()));
157     if (error) {
158         completionHandler(String::fromUTF8(error->message));
159         return;
160     }
161
162     g_subprocess_wait_async(m_browser.get(), m_cancellable.get(), [](GObject* browser, GAsyncResult* result, gpointer userData) {
163         GUniqueOutPtr<GError> error;
164         g_subprocess_wait_finish(G_SUBPROCESS(browser), result, &error.outPtr());
165         if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
166             return;
167         auto* sessionHost = static_cast<SessionHost*>(userData);
168         sessionHost->m_browser = nullptr;
169     }, this);
170
171     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", "127.0.0.1", port));
172     connectToBrowser(std::make_unique<ConnectToBrowserAsyncData>(this, WTFMove(dbusAddress), m_cancellable.get(), WTFMove(completionHandler)));
173 }
174
175 void SessionHost::connectToBrowser(std::unique_ptr<ConnectToBrowserAsyncData>&& data)
176 {
177     if (!m_browser)
178         return;
179
180     RunLoop::main().dispatchAfter(100_ms, [connectToBrowserData = WTFMove(data)]() mutable {
181         auto* data = connectToBrowserData.release();
182         if (g_cancellable_is_cancelled(data->cancellable.get()))
183             return;
184
185         g_dbus_connection_new_for_address(data->dbusAddress.get(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, data->cancellable.get(),
186             [](GObject*, GAsyncResult* result, gpointer userData) {
187                 auto data = std::unique_ptr<ConnectToBrowserAsyncData>(static_cast<ConnectToBrowserAsyncData*>(userData));
188                 GUniqueOutPtr<GError> error;
189                 GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr()));
190                 if (!connection) {
191                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
192                         return;
193
194                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED)) {
195                         data->sessionHost->connectToBrowser(WTFMove(data));
196                         return;
197                     }
198
199                     data->completionHandler(String::fromUTF8(error->message));
200                     return;
201                 }
202                 data->sessionHost->setupConnection(WTFMove(connection));
203                 data->completionHandler(std::nullopt);
204         }, data);
205     });
206 }
207
208 void SessionHost::dbusConnectionClosedCallback(SessionHost* sessionHost)
209 {
210     sessionHost->m_browser = nullptr;
211     sessionHost->inspectorDisconnected();
212 }
213
214 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
215 {
216     GUniqueOutPtr<GError> error;
217     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
218     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
219         WTFLogAlways("RemoteInspectorServer failed to send DBus message: %s", error->message);
220 }
221
222 void SessionHost::setupConnection(GRefPtr<GDBusConnection>&& connection)
223 {
224     ASSERT(!m_dbusConnection);
225     ASSERT(connection);
226     m_dbusConnection = WTFMove(connection);
227
228     g_signal_connect_swapped(m_dbusConnection.get(), "closed", G_CALLBACK(dbusConnectionClosedCallback), this);
229
230     static GDBusNodeInfo* introspectionData = nullptr;
231     if (!introspectionData)
232         introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
233
234     g_dbus_connection_register_object(m_dbusConnection.get(), REMOTE_INSPECTOR_CLIENT_OBJECT_PATH, introspectionData->interfaces[0], &s_interfaceVTable, this, nullptr, nullptr);
235 }
236
237 std::optional<String> SessionHost::matchCapabilities(GVariant* capabilities)
238 {
239     const char* browserName;
240     const char* browserVersion;
241     g_variant_get(capabilities, "(&s&s)", &browserName, &browserVersion);
242
243     if (m_capabilities.browserName) {
244         if (m_capabilities.browserName.value() != browserName)
245             return makeString("expected browserName ", m_capabilities.browserName.value(), " but got ", browserName);
246     } else
247         m_capabilities.browserName = String(browserName);
248
249     if (m_capabilities.browserVersion) {
250         if (!WebDriverService::platformCompareBrowserVersions(m_capabilities.browserVersion.value(), browserVersion))
251             return makeString("requested browserVersion is ", m_capabilities.browserVersion.value(), " but actual version is ", browserVersion);
252     } else
253         m_capabilities.browserVersion = String(browserVersion);
254
255     return std::nullopt;
256 }
257
258 void SessionHost::startAutomationSession(const String& sessionID, Function<void (std::optional<String>)>&& completionHandler)
259 {
260     ASSERT(m_dbusConnection);
261     ASSERT(!m_startSessionCompletionHandler);
262     m_startSessionCompletionHandler = WTFMove(completionHandler);
263     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
264         INSPECTOR_DBUS_OBJECT_PATH,
265         INSPECTOR_DBUS_INTERFACE,
266         "StartAutomationSession",
267         g_variant_new("(s)", sessionID.utf8().data()),
268         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
269         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
270             GUniqueOutPtr<GError> error;
271             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
272             if (!resultVariant && g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
273                 return;
274
275             auto sessionHost = static_cast<SessionHost*>(userData);
276             if (!resultVariant) {
277                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
278                 completionHandler(String("Failed to start automation session"));
279                 return;
280             }
281
282             auto errorString = sessionHost->matchCapabilities(resultVariant.get());
283             if (errorString) {
284                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
285                 completionHandler(errorString);
286                 return;
287             }
288         }, this
289     );
290 }
291
292 void SessionHost::setTargetList(uint64_t connectionID, Vector<Target>&& targetList)
293 {
294     // The server notifies all its clients when connection is lost by sending an empty target list.
295     // We only care about automation connection.
296     if (m_connectionID && m_connectionID != connectionID)
297         return;
298
299     ASSERT(targetList.size() <= 1);
300     if (targetList.isEmpty()) {
301         m_target = Target();
302         m_connectionID = 0;
303         return;
304     }
305
306     m_target = targetList[0];
307     if (m_connectionID) {
308         ASSERT(m_connectionID == connectionID);
309         return;
310     }
311
312     if (!m_startSessionCompletionHandler) {
313         // Session creation was already rejected.
314         return;
315     }
316
317     m_connectionID = connectionID;
318     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
319         INSPECTOR_DBUS_OBJECT_PATH,
320         INSPECTOR_DBUS_INTERFACE,
321         "Setup",
322         g_variant_new("(tt)", m_connectionID, m_target.id),
323         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
324         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
325
326     auto startSessionCompletionHandler = std::exchange(m_startSessionCompletionHandler, nullptr);
327     startSessionCompletionHandler(std::nullopt);
328 }
329
330 void SessionHost::sendMessageToFrontend(uint64_t connectionID, uint64_t targetID, const char* message)
331 {
332     if (connectionID != m_connectionID || targetID != m_target.id)
333         return;
334     dispatchMessage(String::fromUTF8(message));
335 }
336
337 void SessionHost::sendMessageToBackend(const String& message)
338 {
339     ASSERT(m_dbusConnection);
340     ASSERT(m_connectionID);
341     ASSERT(m_target.id);
342
343     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
344         INSPECTOR_DBUS_OBJECT_PATH,
345         INSPECTOR_DBUS_INTERFACE,
346         "SendMessageToBackend",
347         g_variant_new("(tts)", m_connectionID, m_target.id, message.utf8().data()),
348         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
349         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
350 }
351
352 } // namespace WebDriver