Session.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * Copyright (c) 2022, Florent Castelli <florent.castelli@gmail.com>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  6. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "Session.h"
  11. #include "BrowserConnection.h"
  12. #include "Client.h"
  13. #include <AK/NumericLimits.h>
  14. #include <AK/Time.h>
  15. #include <LibCore/LocalServer.h>
  16. #include <LibCore/Stream.h>
  17. #include <LibCore/System.h>
  18. #include <LibGfx/Point.h>
  19. #include <LibGfx/Rect.h>
  20. #include <LibGfx/Size.h>
  21. #include <LibWeb/Cookie/Cookie.h>
  22. #include <LibWeb/Cookie/ParsedCookie.h>
  23. #include <LibWeb/WebDriver/ExecuteScript.h>
  24. #include <unistd.h>
  25. namespace WebDriver {
  26. Session::Session(unsigned session_id, NonnullRefPtr<Client> client)
  27. : m_client(move(client))
  28. , m_id(session_id)
  29. {
  30. }
  31. Session::~Session()
  32. {
  33. if (m_started) {
  34. auto error = stop();
  35. if (error.is_error()) {
  36. warnln("Failed to stop session {}: {}", m_id, error.error());
  37. }
  38. }
  39. }
  40. ErrorOr<Session::Window*, Web::WebDriver::Error> Session::current_window()
  41. {
  42. auto window = m_windows.get(m_current_window_handle);
  43. if (!window.has_value())
  44. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found");
  45. return window.release_value();
  46. }
  47. ErrorOr<void, Web::WebDriver::Error> Session::check_for_open_top_level_browsing_context_or_return_error()
  48. {
  49. (void)TRY(current_window());
  50. return {};
  51. }
  52. ErrorOr<NonnullRefPtr<Core::LocalServer>> Session::create_server(String const& socket_path, ServerType type, NonnullRefPtr<ServerPromise> promise)
  53. {
  54. dbgln("Listening for WebDriver connection on {}", socket_path);
  55. auto server = TRY(Core::LocalServer::try_create());
  56. server->listen(socket_path);
  57. server->on_accept = [this, type, promise](auto client_socket) mutable {
  58. switch (type) {
  59. case ServerType::Browser: {
  60. auto maybe_connection = adopt_nonnull_ref_or_enomem(new (nothrow) BrowserConnection(move(client_socket), m_client, session_id()));
  61. if (maybe_connection.is_error()) {
  62. promise->resolve(maybe_connection.release_error());
  63. return;
  64. }
  65. dbgln("WebDriver is connected to Browser socket");
  66. m_browser_connection = maybe_connection.release_value();
  67. break;
  68. }
  69. case ServerType::WebContent: {
  70. auto maybe_connection = adopt_nonnull_ref_or_enomem(new (nothrow) WebContentConnection(move(client_socket), m_client, session_id()));
  71. if (maybe_connection.is_error()) {
  72. promise->resolve(maybe_connection.release_error());
  73. return;
  74. }
  75. dbgln("WebDriver is connected to WebContent socket");
  76. m_web_content_connection = maybe_connection.release_value();
  77. break;
  78. }
  79. }
  80. if (m_browser_connection && m_web_content_connection)
  81. promise->resolve({});
  82. };
  83. server->on_accept_error = [promise](auto error) mutable {
  84. promise->resolve(move(error));
  85. };
  86. return server;
  87. }
  88. ErrorOr<void> Session::start()
  89. {
  90. auto promise = TRY(ServerPromise::try_create());
  91. auto browser_socket_path = String::formatted("/tmp/webdriver/browser_{}_{}", getpid(), m_id);
  92. auto browser_server = TRY(create_server(browser_socket_path, ServerType::Browser, promise));
  93. auto web_content_socket_path = String::formatted("/tmp/webdriver/content_{}_{}", getpid(), m_id);
  94. auto web_content_server = TRY(create_server(web_content_socket_path, ServerType::WebContent, promise));
  95. char const* argv[] = {
  96. "/bin/Browser",
  97. "--webdriver-browser-path",
  98. browser_socket_path.characters(),
  99. "--webdriver-content-path",
  100. web_content_socket_path.characters(),
  101. nullptr,
  102. };
  103. TRY(Core::System::posix_spawn("/bin/Browser"sv, nullptr, nullptr, const_cast<char**>(argv), environ));
  104. // FIXME: Allow this to be more asynchronous. For now, this at least allows us to propagate
  105. // errors received while accepting the Browser and WebContent sockets.
  106. TRY(promise->await());
  107. m_started = true;
  108. m_windows.set("main", make<Session::Window>("main", true));
  109. m_current_window_handle = "main";
  110. return {};
  111. }
  112. // https://w3c.github.io/webdriver/#dfn-close-the-session
  113. Web::WebDriver::Response Session::stop()
  114. {
  115. // 1. Perform the following substeps based on the remote end’s type:
  116. // NOTE: We perform the "Remote end is an endpoint node" steps in the WebContent process.
  117. m_web_content_connection->close_session();
  118. m_web_content_connection = nullptr;
  119. // 2. Remove the current session from active sessions.
  120. // NOTE: Handled by WebDriver::Client.
  121. // 3. Perform any implementation-specific cleanup steps.
  122. m_browser_connection->async_quit();
  123. m_started = false;
  124. // 4. If an error has occurred in any of the steps above, return the error, otherwise return success with data null.
  125. return JsonValue {};
  126. }
  127. // 9.1 Get Timeouts, https://w3c.github.io/webdriver/#dfn-get-timeouts
  128. JsonObject Session::get_timeouts()
  129. {
  130. // 1. Let timeouts be the timeouts object for session’s timeouts configuration
  131. auto timeouts = timeouts_object(m_timeouts_configuration);
  132. // 2. Return success with data timeouts.
  133. return timeouts;
  134. }
  135. // 9.2 Set Timeouts, https://w3c.github.io/webdriver/#dfn-set-timeouts
  136. Web::WebDriver::Response Session::set_timeouts(JsonValue const& payload)
  137. {
  138. // 1. Let timeouts be the result of trying to JSON deserialize as a timeouts configuration the request’s parameters.
  139. auto timeouts = TRY(json_deserialize_as_a_timeouts_configuration(payload));
  140. // 2. Make the session timeouts the new timeouts.
  141. m_timeouts_configuration = move(timeouts);
  142. // 3. Return success with data null.
  143. return JsonValue {};
  144. }
  145. // 10.3 Back, https://w3c.github.io/webdriver/#dfn-back
  146. Web::WebDriver::Response Session::back()
  147. {
  148. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  149. TRY(check_for_open_top_level_browsing_context_or_return_error());
  150. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  151. // 3. Traverse the history by a delta –1 for the current browsing context.
  152. m_browser_connection->async_back();
  153. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  154. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  155. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  156. // prompts have been handled, return error with error code timeout.
  157. // 6. Return success with data null.
  158. return JsonValue();
  159. }
  160. // 10.4 Forward, https://w3c.github.io/webdriver/#dfn-forward
  161. Web::WebDriver::Response Session::forward()
  162. {
  163. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  164. TRY(check_for_open_top_level_browsing_context_or_return_error());
  165. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  166. // 3. Traverse the history by a delta 1 for the current browsing context.
  167. m_browser_connection->async_forward();
  168. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  169. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  170. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  171. // prompts have been handled, return error with error code timeout.
  172. // 6. Return success with data null.
  173. return JsonValue();
  174. }
  175. // 10.5 Refresh, https://w3c.github.io/webdriver/#dfn-refresh
  176. Web::WebDriver::Response Session::refresh()
  177. {
  178. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  179. TRY(check_for_open_top_level_browsing_context_or_return_error());
  180. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  181. // 3. Initiate an overridden reload of the current top-level browsing context’s active document.
  182. m_browser_connection->async_refresh();
  183. // FIXME: 4. If url is special except for file:
  184. // FIXME: 1. Try to wait for navigation to complete.
  185. // FIXME: 2. Try to run the post-navigation checks.
  186. // FIXME: 5. Set the current browsing context with current top-level browsing context.
  187. // 6. Return success with data null.
  188. return JsonValue();
  189. }
  190. // 10.6 Get Title, https://w3c.github.io/webdriver/#dfn-get-title
  191. Web::WebDriver::Response Session::get_title()
  192. {
  193. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  194. TRY(check_for_open_top_level_browsing_context_or_return_error());
  195. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  196. // 3. Let title be the initial value of the title IDL attribute of the current top-level browsing context's active document.
  197. // 4. Return success with data title.
  198. return JsonValue(m_browser_connection->get_title());
  199. }
  200. // 11.1 Get Window Handle, https://w3c.github.io/webdriver/#get-window-handle
  201. Web::WebDriver::Response Session::get_window_handle()
  202. {
  203. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  204. TRY(check_for_open_top_level_browsing_context_or_return_error());
  205. // 2. Return success with data being the window handle associated with the current top-level browsing context.
  206. return JsonValue { m_current_window_handle };
  207. }
  208. // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window
  209. ErrorOr<void, Variant<Web::WebDriver::Error, Error>> Session::close_window()
  210. {
  211. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  212. TRY(check_for_open_top_level_browsing_context_or_return_error());
  213. // 2. Close the current top-level browsing context.
  214. m_windows.remove(m_current_window_handle);
  215. // 3. If there are no more open top-level browsing contexts, then close the session.
  216. if (m_windows.is_empty()) {
  217. auto result = stop();
  218. if (result.is_error()) {
  219. return Variant<Web::WebDriver::Error, Error>(result.release_error());
  220. }
  221. }
  222. return {};
  223. }
  224. // 11.4 Get Window Handles, https://w3c.github.io/webdriver/#dfn-get-window-handles
  225. Web::WebDriver::Response Session::get_window_handles() const
  226. {
  227. // 1. Let handles be a JSON List.
  228. auto handles = JsonArray {};
  229. // 2. For each top-level browsing context in the remote end, push the associated window handle onto handles.
  230. for (auto const& window_handle : m_windows.keys())
  231. handles.append(window_handle);
  232. // 3. Return success with data handles.
  233. return JsonValue { handles };
  234. }
  235. // 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
  236. Web::WebDriver::Response Session::add_cookie(JsonValue const& payload)
  237. {
  238. // 1. Let data be the result of getting a property named cookie from the parameters argument.
  239. if (!payload.is_object() || !payload.as_object().has_object("cookie"sv))
  240. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a cookie object");
  241. auto const& maybe_data = payload.as_object().get("cookie"sv);
  242. // 2. If data is not a JSON Object with all the required (non-optional) JSON keys listed in the table for cookie conversion,
  243. // return error with error code invalid argument.
  244. // NOTE: Table is here: https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion
  245. if (!maybe_data.is_object())
  246. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Value \"cookie\' is not an object");
  247. auto const& data = maybe_data.as_object();
  248. if (!data.has("name"sv) || !data.has("value"sv))
  249. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object doesn't contain all required keys");
  250. // 3. If the current browsing context is no longer open, return error with error code no such window.
  251. TRY(check_for_open_top_level_browsing_context_or_return_error());
  252. // FIXME: 4. Handle any user prompts, and return its value if it is an error.
  253. // FIXME: 5. If the current browsing context’s document element is a cookie-averse Document object,
  254. // return error with error code invalid cookie domain.
  255. // 6. If cookie name or cookie value is null,
  256. // FIXME: cookie domain is not equal to the current browsing context’s active document’s domain,
  257. // cookie secure only or cookie HTTP only are not boolean types,
  258. // or cookie expiry time is not an integer type, or it less than 0 or greater than the maximum safe integer,
  259. // return error with error code invalid argument.
  260. if (data.get("name"sv).is_null() || data.get("value"sv).is_null())
  261. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: name or value are null");
  262. if (data.has("secure"sv) && !data.get("secure"sv).is_bool())
  263. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: secure is not bool");
  264. if (data.has("httpOnly"sv) && !data.get("httpOnly"sv).is_bool())
  265. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: httpOnly is not bool");
  266. Optional<Core::DateTime> expiry_time;
  267. if (data.has("expiry"sv)) {
  268. auto expiry_argument = data.get("expiry"sv);
  269. if (!expiry_argument.is_u32()) {
  270. // NOTE: less than 0 or greater than safe integer are handled by the JSON parser
  271. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: expiry is not u32");
  272. }
  273. expiry_time = Core::DateTime::from_timestamp(expiry_argument.as_u32());
  274. }
  275. // 7. Create a cookie in the cookie store associated with the active document’s address using
  276. // cookie name name, cookie value value, and an attribute-value list of the following cookie concepts
  277. // listed in the table for cookie conversion from data:
  278. Web::Cookie::ParsedCookie cookie;
  279. if (auto name_attribute = data.get("name"sv); name_attribute.is_string())
  280. cookie.name = name_attribute.as_string();
  281. else
  282. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect name attribute to be string");
  283. if (auto value_attribute = data.get("value"sv); value_attribute.is_string())
  284. cookie.value = value_attribute.as_string();
  285. else
  286. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect value attribute to be string");
  287. // Cookie path
  288. // The value if the entry exists, otherwise "/".
  289. if (data.has("path"sv)) {
  290. if (auto path_attribute = data.get("path"sv); path_attribute.is_string())
  291. cookie.path = path_attribute.as_string();
  292. else
  293. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect path attribute to be string");
  294. } else {
  295. cookie.path = "/";
  296. }
  297. // Cookie domain
  298. // The value if the entry exists, otherwise the current browsing context’s active document’s URL domain.
  299. // NOTE: The otherwise case is handled by the CookieJar
  300. if (data.has("domain"sv)) {
  301. if (auto domain_attribute = data.get("domain"sv); domain_attribute.is_string())
  302. cookie.domain = domain_attribute.as_string();
  303. else
  304. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect domain attribute to be string");
  305. }
  306. // Cookie secure only
  307. // The value if the entry exists, otherwise false.
  308. if (data.has("secure"sv)) {
  309. cookie.secure_attribute_present = data.get("secure"sv).as_bool();
  310. } else {
  311. cookie.secure_attribute_present = false;
  312. }
  313. // Cookie HTTP only
  314. // The value if the entry exists, otherwise false.
  315. if (data.has("httpOnly"sv)) {
  316. cookie.http_only_attribute_present = data.get("httpOnly"sv).as_bool();
  317. } else {
  318. cookie.http_only_attribute_present = false;
  319. }
  320. // Cookie expiry time
  321. // The value if the entry exists, otherwise leave unset to indicate that this is a session cookie.
  322. cookie.expiry_time_from_expires_attribute = expiry_time;
  323. // FIXME: Cookie same site
  324. // The value if the entry exists, otherwise leave unset to indicate that no same site policy is defined.
  325. m_browser_connection->async_add_cookie(move(cookie));
  326. // If there is an error during this step, return error with error code unable to set cookie.
  327. // NOTE: This probably should only apply to the actual setting of the cookie in the Browser,
  328. // which cannot fail in our case.
  329. // Thus, the error-codes used above are 400 "invalid argument".
  330. // 8. Return success with data null.
  331. return JsonValue();
  332. }
  333. // https://w3c.github.io/webdriver/#dfn-delete-cookies
  334. void Session::delete_cookies(Optional<StringView> const& name)
  335. {
  336. // For each cookie among all associated cookies of the current browsing context’s active document,
  337. // run the substeps of the first matching condition:
  338. for (auto& cookie : m_browser_connection->get_all_cookies()) {
  339. // -> name is undefined
  340. // -> name is equal to cookie name
  341. if (!name.has_value() || name.value() == cookie.name) {
  342. // Set the cookie expiry time to a Unix timestamp in the past.
  343. cookie.expiry_time = Core::DateTime::from_timestamp(0);
  344. m_browser_connection->async_update_cookie(cookie);
  345. }
  346. // -> Otherwise
  347. // Do nothing.
  348. }
  349. }
  350. // 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
  351. Web::WebDriver::Response Session::delete_cookie(StringView name)
  352. {
  353. // 1. If the current browsing context is no longer open, return error with error code no such window.
  354. TRY(check_for_open_top_level_browsing_context_or_return_error());
  355. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  356. // 3. Delete cookies using the url variable name parameter as the filter argument.
  357. delete_cookies(name);
  358. // 4. Return success with data null.
  359. return JsonValue();
  360. }
  361. // 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
  362. Web::WebDriver::Response Session::delete_all_cookies()
  363. {
  364. // 1. If the current browsing context is no longer open, return error with error code no such window.
  365. TRY(check_for_open_top_level_browsing_context_or_return_error());
  366. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  367. // 3. Delete cookies, giving no filtering argument.
  368. delete_cookies();
  369. // 4. Return success with data null.
  370. return JsonValue();
  371. }
  372. }