[CMake] Properly test if compiler supports compiler flags
[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     nullptr
99 };
100
101 void SessionHost::connectToBrowser(Function<void (Succeeded)>&& completionHandler)
102 {
103     launchBrowser(WTFMove(completionHandler));
104 }
105
106 struct ConnectToBrowserAsyncData {
107     ConnectToBrowserAsyncData(SessionHost* sessionHost, GUniquePtr<char>&& dbusAddress, GCancellable* cancellable, Function<void (SessionHost::Succeeded)>&& completionHandler)
108         : sessionHost(sessionHost)
109         , dbusAddress(WTFMove(dbusAddress))
110         , cancellable(cancellable)
111         , completionHandler(WTFMove(completionHandler))
112     {
113     }
114
115     SessionHost* sessionHost;
116     GUniquePtr<char> dbusAddress;
117     GRefPtr<GCancellable> cancellable;
118     Function<void (SessionHost::Succeeded)> completionHandler;
119 };
120
121 static guint16 freePort()
122 {
123     GRefPtr<GSocket> socket = adoptGRef(g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, nullptr));
124     GRefPtr<GInetAddress> loopbackAdress = adoptGRef(g_inet_address_new_loopback(G_SOCKET_FAMILY_IPV4));
125     GRefPtr<GSocketAddress> address = adoptGRef(g_inet_socket_address_new(loopbackAdress.get(), 0));
126     g_socket_bind(socket.get(), address.get(), FALSE, nullptr);
127     g_socket_listen(socket.get(), nullptr);
128     address = adoptGRef(g_socket_get_local_address(socket.get(), nullptr));
129     g_socket_close(socket.get(), nullptr);
130     return g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(address.get()));
131 }
132
133 void SessionHost::launchBrowser(Function<void (Succeeded)>&& completionHandler)
134 {
135     m_cancellable = adoptGRef(g_cancellable_new());
136     GRefPtr<GSubprocessLauncher> launcher = adoptGRef(g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_NONE));
137     guint16 port = freePort();
138     GUniquePtr<char> inspectorAddress(g_strdup_printf("127.0.0.1:%u", port));
139     g_subprocess_launcher_setenv(launcher.get(), "WEBKIT_INSPECTOR_SERVER", inspectorAddress.get(), TRUE);
140 #if PLATFORM(GTK)
141     g_subprocess_launcher_setenv(launcher.get(), "GTK_OVERLAY_SCROLLING", m_capabilities.useOverlayScrollbars.value() ? "1" : "0", TRUE);
142 #endif
143
144     const auto& browserArguments = m_capabilities.browserArguments.value();
145     GUniquePtr<char*> args(g_new0(char*, browserArguments.size() + 2));
146     args.get()[0] = g_strdup(m_capabilities.browserBinary.value().utf8().data());
147     for (unsigned i = 0; i < browserArguments.size(); ++i)
148         args.get()[i + 1] = g_strdup(browserArguments[i].utf8().data());
149
150     m_browser = adoptGRef(g_subprocess_launcher_spawnv(launcher.get(), args.get(), nullptr));
151     g_subprocess_wait_async(m_browser.get(), m_cancellable.get(), [](GObject* browser, GAsyncResult* result, gpointer userData) {
152         GUniqueOutPtr<GError> error;
153         g_subprocess_wait_finish(G_SUBPROCESS(browser), result, &error.outPtr());
154         if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
155             return;
156         auto* sessionHost = static_cast<SessionHost*>(userData);
157         sessionHost->m_browser = nullptr;
158     }, this);
159
160     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", "127.0.0.1", port));
161     connectToBrowser(std::make_unique<ConnectToBrowserAsyncData>(this, WTFMove(dbusAddress), m_cancellable.get(), WTFMove(completionHandler)));
162 }
163
164 void SessionHost::connectToBrowser(std::unique_ptr<ConnectToBrowserAsyncData>&& data)
165 {
166     if (!m_browser)
167         return;
168
169     RunLoop::main().dispatchAfter(100_ms, [connectToBrowserData = WTFMove(data)]() mutable {
170         auto* data = connectToBrowserData.release();
171         if (g_cancellable_is_cancelled(data->cancellable.get()))
172             return;
173
174         g_dbus_connection_new_for_address(data->dbusAddress.get(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, data->cancellable.get(),
175             [](GObject*, GAsyncResult* result, gpointer userData) {
176                 auto data = std::unique_ptr<ConnectToBrowserAsyncData>(static_cast<ConnectToBrowserAsyncData*>(userData));
177                 GUniqueOutPtr<GError> error;
178                 GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr()));
179                 if (!connection) {
180                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
181                         return;
182
183                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED)) {
184                         data->sessionHost->connectToBrowser(WTFMove(data));
185                         return;
186                     }
187
188                     data->completionHandler(Succeeded::No);
189                     return;
190                 }
191                 data->sessionHost->setupConnection(WTFMove(connection), WTFMove(data->completionHandler));
192         }, data);
193     });
194 }
195
196 void SessionHost::dbusConnectionClosedCallback(SessionHost* sessionHost)
197 {
198     sessionHost->inspectorDisconnected();
199 }
200
201 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
202 {
203     GUniqueOutPtr<GError> error;
204     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
205     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
206         WTFLogAlways("RemoteInspectorServer failed to send DBus message: %s", error->message);
207 }
208
209 void SessionHost::setupConnection(GRefPtr<GDBusConnection>&& connection, Function<void (Succeeded)>&& completionHandler)
210 {
211     ASSERT(!m_dbusConnection);
212     ASSERT(connection);
213     m_dbusConnection = WTFMove(connection);
214
215     g_signal_connect_swapped(m_dbusConnection.get(), "closed", G_CALLBACK(dbusConnectionClosedCallback), this);
216
217     static GDBusNodeInfo* introspectionData = nullptr;
218     if (!introspectionData)
219         introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
220
221     g_dbus_connection_register_object(m_dbusConnection.get(), REMOTE_INSPECTOR_CLIENT_OBJECT_PATH, introspectionData->interfaces[0], &s_interfaceVTable, this, nullptr, nullptr);
222
223     completionHandler(Succeeded::Yes);
224 }
225
226 std::optional<String> SessionHost::matchCapabilities(GVariant* capabilities)
227 {
228     const char* browserName;
229     const char* browserVersion;
230     g_variant_get(capabilities, "(&s&s)", &browserName, &browserVersion);
231
232     if (m_capabilities.browserName) {
233         if (m_capabilities.browserName.value() != browserName)
234             return makeString("expected browserName ", m_capabilities.browserName.value(), " but got ", browserName);
235     } else
236         m_capabilities.browserName = String(browserName);
237
238     if (m_capabilities.browserVersion) {
239         if (!WebDriverService::platformCompareBrowserVersions(m_capabilities.browserVersion.value(), browserVersion))
240             return makeString("requested browserVersion is ", m_capabilities.browserVersion.value(), " but actual version is ", browserVersion);
241     } else
242         m_capabilities.browserVersion = String(browserVersion);
243
244     return std::nullopt;
245 }
246
247 void SessionHost::startAutomationSession(const String& sessionID, Function<void (std::optional<String>)>&& completionHandler)
248 {
249     ASSERT(m_dbusConnection);
250     ASSERT(!m_startSessionCompletionHandler);
251     m_startSessionCompletionHandler = WTFMove(completionHandler);
252     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
253         INSPECTOR_DBUS_OBJECT_PATH,
254         INSPECTOR_DBUS_INTERFACE,
255         "StartAutomationSession",
256         g_variant_new("(s)", sessionID.utf8().data()),
257         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
258         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
259             GUniqueOutPtr<GError> error;
260             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
261             if (!resultVariant && g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
262                 return;
263
264             auto sessionHost = static_cast<SessionHost*>(userData);
265             if (!resultVariant) {
266                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
267                 completionHandler(String("Failed to start automation session"));
268                 return;
269             }
270
271             auto errorString = sessionHost->matchCapabilities(resultVariant.get());
272             if (errorString) {
273                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
274                 completionHandler(errorString);
275                 return;
276             }
277         }, this
278     );
279 }
280
281 void SessionHost::setTargetList(uint64_t connectionID, Vector<Target>&& targetList)
282 {
283     // The server notifies all its clients when connection is lost by sending an empty target list.
284     // We only care about automation connection.
285     if (m_connectionID && m_connectionID != connectionID)
286         return;
287
288     ASSERT(targetList.size() <= 1);
289     if (targetList.isEmpty()) {
290         m_target = Target();
291         m_connectionID = 0;
292         return;
293     }
294
295     m_target = targetList[0];
296     if (m_connectionID) {
297         ASSERT(m_connectionID == connectionID);
298         return;
299     }
300
301     if (!m_startSessionCompletionHandler) {
302         // Session creation was already rejected.
303         return;
304     }
305
306     m_connectionID = connectionID;
307     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
308         INSPECTOR_DBUS_OBJECT_PATH,
309         INSPECTOR_DBUS_INTERFACE,
310         "Setup",
311         g_variant_new("(tt)", m_connectionID, m_target.id),
312         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
313         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
314
315     auto startSessionCompletionHandler = std::exchange(m_startSessionCompletionHandler, nullptr);
316     startSessionCompletionHandler(std::nullopt);
317 }
318
319 void SessionHost::sendMessageToFrontend(uint64_t connectionID, uint64_t targetID, const char* message)
320 {
321     if (connectionID != m_connectionID || targetID != m_target.id)
322         return;
323     dispatchMessage(String::fromUTF8(message));
324 }
325
326 void SessionHost::sendMessageToBackend(const String& message)
327 {
328     ASSERT(m_dbusConnection);
329     ASSERT(m_connectionID);
330     ASSERT(m_target.id);
331
332     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
333         INSPECTOR_DBUS_OBJECT_PATH,
334         INSPECTOR_DBUS_INTERFACE,
335         "SendMessageToBackend",
336         g_variant_new("(tts)", m_connectionID, m_target.id, message.utf8().data()),
337         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
338         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
339 }
340
341 } // namespace WebDriver