[WTF] Add makeUnique<T>, which ensures T is fast-allocated, makeUnique / makeUniqueWi...
[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     if (m_dbusConnection)
45         g_signal_handlers_disconnect_matched(m_dbusConnection.get(), G_SIGNAL_MATCH_DATA, 0, 0, nullptr, nullptr, this);
46     g_cancellable_cancel(m_cancellable.get());
47     if (m_browser)
48         g_subprocess_force_exit(m_browser.get());
49 }
50
51 static const char introspectionXML[] =
52     "<node>"
53     "  <interface name='" REMOTE_INSPECTOR_CLIENT_DBUS_INTERFACE "'>"
54     "    <method name='SetTargetList'>"
55     "      <arg type='t' name='connectionID' direction='in'/>"
56     "      <arg type='a(tsssb)' name='list' direction='in'/>"
57     "    </method>"
58     "    <method name='SendMessageToFrontend'>"
59     "      <arg type='t' name='connectionID' direction='in'/>"
60     "      <arg type='t' name='target' direction='in'/>"
61     "      <arg type='s' name='message' direction='in'/>"
62     "    </method>"
63     "  </interface>"
64     "</node>";
65
66 const GDBusInterfaceVTable SessionHost::s_interfaceVTable = {
67     // method_call
68     [](GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) {
69         auto* sessionHost = static_cast<SessionHost*>(userData);
70         if (!g_strcmp0(methodName, "SetTargetList")) {
71             guint64 connectionID;
72             GUniqueOutPtr<GVariantIter> iter;
73             g_variant_get(parameters, "(ta(tsssb))", &connectionID, &iter.outPtr());
74             size_t targetCount = g_variant_iter_n_children(iter.get());
75             Vector<SessionHost::Target> targetList;
76             targetList.reserveInitialCapacity(targetCount);
77             guint64 targetID;
78             const char* type;
79             const char* name;
80             const char* dummy;
81             gboolean isPaired;
82             while (g_variant_iter_loop(iter.get(), "(t&s&s&sb)", &targetID, &type, &name, &dummy, &isPaired)) {
83                 if (!g_strcmp0(type, "Automation"))
84                     targetList.uncheckedAppend({ targetID, name, static_cast<bool>(isPaired) });
85             }
86             sessionHost->setTargetList(connectionID, WTFMove(targetList));
87             g_dbus_method_invocation_return_value(invocation, nullptr);
88         } else if (!g_strcmp0(methodName, "SendMessageToFrontend")) {
89             guint64 connectionID, targetID;
90             const char* message;
91             g_variant_get(parameters, "(tt&s)", &connectionID, &targetID, &message);
92             sessionHost->sendMessageToFrontend(connectionID, targetID, message);
93             g_dbus_method_invocation_return_value(invocation, nullptr);
94         }
95     },
96     // get_property
97     nullptr,
98     // set_property
99     nullptr,
100     // padding
101     { 0 }
102 };
103
104 void SessionHost::connectToBrowser(Function<void (Optional<String> error)>&& completionHandler)
105 {
106     launchBrowser(WTFMove(completionHandler));
107 }
108
109 bool SessionHost::isConnected() const
110 {
111     // Session is connected when launching or when dbus connection hasn't been closed.
112     return m_browser && (!m_dbusConnection || !g_dbus_connection_is_closed(m_dbusConnection.get()));
113 }
114
115 struct ConnectToBrowserAsyncData {
116     WTF_MAKE_STRUCT_FAST_ALLOCATED;
117     ConnectToBrowserAsyncData(SessionHost* sessionHost, GUniquePtr<char>&& dbusAddress, GCancellable* cancellable, Function<void (Optional<String> error)>&& completionHandler)
118         : sessionHost(sessionHost)
119         , dbusAddress(WTFMove(dbusAddress))
120         , cancellable(cancellable)
121         , completionHandler(WTFMove(completionHandler))
122     {
123     }
124
125     SessionHost* sessionHost;
126     GUniquePtr<char> dbusAddress;
127     GRefPtr<GCancellable> cancellable;
128     Function<void (Optional<String> error)> completionHandler;
129 };
130
131 static guint16 freePort()
132 {
133     GRefPtr<GSocket> socket = adoptGRef(g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, nullptr));
134     GRefPtr<GInetAddress> loopbackAdress = adoptGRef(g_inet_address_new_loopback(G_SOCKET_FAMILY_IPV4));
135     GRefPtr<GSocketAddress> address = adoptGRef(g_inet_socket_address_new(loopbackAdress.get(), 0));
136     g_socket_bind(socket.get(), address.get(), FALSE, nullptr);
137     g_socket_listen(socket.get(), nullptr);
138     address = adoptGRef(g_socket_get_local_address(socket.get(), nullptr));
139     g_socket_close(socket.get(), nullptr);
140     return g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(address.get()));
141 }
142
143 void SessionHost::launchBrowser(Function<void (Optional<String> error)>&& completionHandler)
144 {
145     m_cancellable = adoptGRef(g_cancellable_new());
146     GRefPtr<GSubprocessLauncher> launcher = adoptGRef(g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_NONE));
147     guint16 port = freePort();
148     GUniquePtr<char> inspectorAddress(g_strdup_printf("127.0.0.1:%u", port));
149     g_subprocess_launcher_setenv(launcher.get(), "WEBKIT_INSPECTOR_SERVER", inspectorAddress.get(), TRUE);
150 #if PLATFORM(GTK)
151     g_subprocess_launcher_setenv(launcher.get(), "GTK_OVERLAY_SCROLLING", m_capabilities.useOverlayScrollbars.value() ? "1" : "0", TRUE);
152 #endif
153
154     size_t browserArgumentsSize = m_capabilities.browserArguments ? m_capabilities.browserArguments->size() : 0;
155     GUniquePtr<char*> args(g_new0(char*, browserArgumentsSize + 2));
156     args.get()[0] = g_strdup(m_capabilities.browserBinary.value().utf8().data());
157     for (unsigned i = 0; i < browserArgumentsSize; ++i)
158         args.get()[i + 1] = g_strdup(m_capabilities.browserArguments.value()[i].utf8().data());
159
160     GUniqueOutPtr<GError> error;
161     m_browser = adoptGRef(g_subprocess_launcher_spawnv(launcher.get(), args.get(), &error.outPtr()));
162     if (error) {
163         completionHandler(String::fromUTF8(error->message));
164         return;
165     }
166
167     g_subprocess_wait_async(m_browser.get(), m_cancellable.get(), [](GObject* browser, GAsyncResult* result, gpointer userData) {
168         GUniqueOutPtr<GError> error;
169         g_subprocess_wait_finish(G_SUBPROCESS(browser), result, &error.outPtr());
170         if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
171             return;
172         auto* sessionHost = static_cast<SessionHost*>(userData);
173         sessionHost->m_browser = nullptr;
174     }, this);
175
176     GUniquePtr<char> dbusAddress(g_strdup_printf("tcp:host=%s,port=%u", "127.0.0.1", port));
177     connectToBrowser(makeUnique<ConnectToBrowserAsyncData>(this, WTFMove(dbusAddress), m_cancellable.get(), WTFMove(completionHandler)));
178 }
179
180 void SessionHost::connectToBrowser(std::unique_ptr<ConnectToBrowserAsyncData>&& data)
181 {
182     if (!m_browser)
183         return;
184
185     RunLoop::main().dispatchAfter(100_ms, [connectToBrowserData = WTFMove(data)]() mutable {
186         auto* data = connectToBrowserData.release();
187         if (g_cancellable_is_cancelled(data->cancellable.get()))
188             return;
189
190         g_dbus_connection_new_for_address(data->dbusAddress.get(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, data->cancellable.get(),
191             [](GObject*, GAsyncResult* result, gpointer userData) {
192                 auto data = std::unique_ptr<ConnectToBrowserAsyncData>(static_cast<ConnectToBrowserAsyncData*>(userData));
193                 GUniqueOutPtr<GError> error;
194                 GRefPtr<GDBusConnection> connection = adoptGRef(g_dbus_connection_new_for_address_finish(result, &error.outPtr()));
195                 if (!connection) {
196                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
197                         return;
198
199                     if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CONNECTION_REFUSED)) {
200                         data->sessionHost->connectToBrowser(WTFMove(data));
201                         return;
202                     }
203
204                     data->completionHandler(String::fromUTF8(error->message));
205                     return;
206                 }
207                 data->sessionHost->setupConnection(WTFMove(connection));
208                 data->completionHandler(WTF::nullopt);
209         }, data);
210     });
211 }
212
213 void SessionHost::dbusConnectionClosedCallback(SessionHost* sessionHost)
214 {
215     sessionHost->m_browser = nullptr;
216     sessionHost->inspectorDisconnected();
217 }
218
219 static void dbusConnectionCallAsyncReadyCallback(GObject* source, GAsyncResult* result, gpointer)
220 {
221     GUniqueOutPtr<GError> error;
222     GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
223     if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
224         WTFLogAlways("RemoteInspectorServer failed to send DBus message: %s", error->message);
225 }
226
227 void SessionHost::setupConnection(GRefPtr<GDBusConnection>&& connection)
228 {
229     ASSERT(!m_dbusConnection);
230     ASSERT(connection);
231     m_dbusConnection = WTFMove(connection);
232
233     g_signal_connect_swapped(m_dbusConnection.get(), "closed", G_CALLBACK(dbusConnectionClosedCallback), this);
234
235     static GDBusNodeInfo* introspectionData = nullptr;
236     if (!introspectionData)
237         introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, nullptr);
238
239     g_dbus_connection_register_object(m_dbusConnection.get(), REMOTE_INSPECTOR_CLIENT_OBJECT_PATH, introspectionData->interfaces[0], &s_interfaceVTable, this, nullptr, nullptr);
240 }
241
242 static bool matchBrowserOptions(const String& browserName, const String& browserVersion, const Capabilities& capabilities)
243 {
244     if (capabilities.browserName && capabilities.browserName.value() != browserName)
245         return false;
246
247     if (capabilities.browserVersion && !WebDriverService::platformCompareBrowserVersions(capabilities.browserVersion.value(), browserVersion))
248         return false;
249
250     return true;
251 }
252
253 bool SessionHost::matchCapabilities(GVariant* capabilities)
254 {
255     const char* name;
256     const char* version;
257     g_variant_get(capabilities, "(&s&s)", &name, &version);
258
259     auto browserName = String::fromUTF8(name);
260     auto browserVersion = String::fromUTF8(version);
261     bool didMatch = matchBrowserOptions(browserName, browserVersion, m_capabilities);
262     m_capabilities.browserName = browserName;
263     m_capabilities.browserVersion = browserVersion;
264
265     return didMatch;
266 }
267
268 bool SessionHost::buildSessionCapabilities(GVariantBuilder* builder) const
269 {
270     if (!m_capabilities.acceptInsecureCerts && !m_capabilities.certificates)
271         return false;
272
273     g_variant_builder_init(builder, G_VARIANT_TYPE("a{sv}"));
274     if (m_capabilities.acceptInsecureCerts)
275         g_variant_builder_add(builder, "{sv}", "acceptInsecureCerts", g_variant_new_boolean(m_capabilities.acceptInsecureCerts.value()));
276
277     if (m_capabilities.certificates) {
278         GVariantBuilder arrayBuilder;
279         g_variant_builder_init(&arrayBuilder, G_VARIANT_TYPE("a(ss)"));
280         for (auto& certificate : *m_capabilities.certificates) {
281             g_variant_builder_add_value(&arrayBuilder, g_variant_new("(ss)",
282                 certificate.first.utf8().data(), certificate.second.utf8().data()));
283         }
284         g_variant_builder_add(builder, "{sv}", "certificates", g_variant_builder_end(&arrayBuilder));
285     }
286
287     return true;
288 }
289
290 void SessionHost::startAutomationSession(Function<void (bool, Optional<String>)>&& completionHandler)
291 {
292     ASSERT(m_dbusConnection);
293     ASSERT(!m_startSessionCompletionHandler);
294     m_startSessionCompletionHandler = WTFMove(completionHandler);
295     m_sessionID = createCanonicalUUIDString();
296     GVariantBuilder builder;
297     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
298         INSPECTOR_DBUS_OBJECT_PATH,
299         INSPECTOR_DBUS_INTERFACE,
300         "StartAutomationSession",
301         g_variant_new("(sa{sv})", m_sessionID.utf8().data(), buildSessionCapabilities(&builder) ? &builder : nullptr),
302         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
303         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
304             GUniqueOutPtr<GError> error;
305             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
306             if (!resultVariant && g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
307                 return;
308
309             auto sessionHost = static_cast<SessionHost*>(userData);
310             if (!resultVariant) {
311                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
312                 completionHandler(false, makeString("Failed to start automation session: ", String::fromUTF8(error->message)));
313                 return;
314             }
315
316             if (!sessionHost->matchCapabilities(resultVariant.get())) {
317                 auto completionHandler = std::exchange(sessionHost->m_startSessionCompletionHandler, nullptr);
318                 completionHandler(false, WTF::nullopt);
319                 return;
320             }
321         }, this
322     );
323 }
324
325 void SessionHost::setTargetList(uint64_t connectionID, Vector<Target>&& targetList)
326 {
327     // The server notifies all its clients when connection is lost by sending an empty target list.
328     // We only care about automation connection.
329     if (m_connectionID && m_connectionID != connectionID)
330         return;
331
332     ASSERT(targetList.size() <= 1);
333     if (targetList.isEmpty()) {
334         m_target = Target();
335         if (m_connectionID) {
336             if (m_dbusConnection)
337                 g_dbus_connection_close(m_dbusConnection.get(), nullptr, nullptr, nullptr);
338             m_connectionID = 0;
339         }
340         return;
341     }
342
343     m_target = targetList[0];
344     if (m_connectionID) {
345         ASSERT(m_connectionID == connectionID);
346         return;
347     }
348
349     if (!m_startSessionCompletionHandler) {
350         // Session creation was already rejected.
351         return;
352     }
353
354     m_connectionID = connectionID;
355     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
356         INSPECTOR_DBUS_OBJECT_PATH,
357         INSPECTOR_DBUS_INTERFACE,
358         "Setup",
359         g_variant_new("(tt)", m_connectionID, m_target.id),
360         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
361         -1, m_cancellable.get(), dbusConnectionCallAsyncReadyCallback, nullptr);
362
363     auto startSessionCompletionHandler = std::exchange(m_startSessionCompletionHandler, nullptr);
364     startSessionCompletionHandler(true, WTF::nullopt);
365 }
366
367 void SessionHost::sendMessageToFrontend(uint64_t connectionID, uint64_t targetID, const char* message)
368 {
369     if (connectionID != m_connectionID || targetID != m_target.id)
370         return;
371     dispatchMessage(String::fromUTF8(message));
372 }
373
374 struct MessageContext {
375     WTF_MAKE_STRUCT_FAST_ALLOCATED;
376     long messageID;
377     SessionHost* host;
378 };
379
380 void SessionHost::sendMessageToBackend(long messageID, const String& message)
381 {
382     ASSERT(m_dbusConnection);
383     ASSERT(m_connectionID);
384     ASSERT(m_target.id);
385
386     auto messageContext = makeUnique<MessageContext>(MessageContext { messageID, this });
387     g_dbus_connection_call(m_dbusConnection.get(), nullptr,
388         INSPECTOR_DBUS_OBJECT_PATH,
389         INSPECTOR_DBUS_INTERFACE,
390         "SendMessageToBackend",
391         g_variant_new("(tts)", m_connectionID, m_target.id, message.utf8().data()),
392         nullptr, G_DBUS_CALL_FLAGS_NO_AUTO_START,
393         -1, m_cancellable.get(), [](GObject* source, GAsyncResult* result, gpointer userData) {
394             auto messageContext = std::unique_ptr<MessageContext>(static_cast<MessageContext*>(userData));
395             GUniqueOutPtr<GError> error;
396             GRefPtr<GVariant> resultVariant = adoptGRef(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &error.outPtr()));
397             if (!resultVariant && !g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
398                 auto responseHandler = messageContext->host->m_commandRequests.take(messageContext->messageID);
399                 if (responseHandler) {
400                     auto errorObject = JSON::Object::create();
401                     errorObject->setInteger("code"_s, -32603);
402                     errorObject->setString("message"_s, String::fromUTF8(error->message));
403                     responseHandler({ WTFMove(errorObject), true });
404                 }
405             }
406         }, messageContext.release());
407 }
408
409 } // namespace WebDriver