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