Client.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Debug.h>
  10. #include <AK/JsonParser.h>
  11. #include <LibCore/DateTime.h>
  12. #include <LibCore/MemoryStream.h>
  13. #include <LibHTTP/HttpRequest.h>
  14. #include <LibHTTP/HttpResponse.h>
  15. #include <WebDriver/Client.h>
  16. #include <WebDriver/Session.h>
  17. #include <WebDriver/TimeoutsConfiguration.h>
  18. namespace WebDriver {
  19. Atomic<unsigned> Client::s_next_session_id;
  20. NonnullOwnPtrVector<Session> Client::s_sessions;
  21. Vector<Client::Route> Client::s_routes = {
  22. { HTTP::HttpRequest::Method::POST, { "session" }, &Client::handle_new_session },
  23. { HTTP::HttpRequest::Method::DELETE, { "session", ":session_id" }, &Client::handle_delete_session },
  24. { HTTP::HttpRequest::Method::GET, { "status" }, &Client::handle_get_status },
  25. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "timeouts" }, &Client::handle_get_timeouts },
  26. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "timeouts" }, &Client::handle_set_timeouts },
  27. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "url" }, &Client::handle_navigate_to },
  28. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "url" }, &Client::handle_get_current_url },
  29. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "back" }, &Client::handle_back },
  30. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "forward" }, &Client::handle_forward },
  31. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "refresh" }, &Client::handle_refresh },
  32. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "title" }, &Client::handle_get_title },
  33. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "window" }, &Client::handle_get_window_handle },
  34. { HTTP::HttpRequest::Method::DELETE, { "session", ":session_id", "window" }, &Client::handle_close_window },
  35. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "element" }, &Client::handle_find_element },
  36. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "elements" }, &Client::handle_find_elements },
  37. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "element", ":element_id", "element" }, &Client::handle_find_element_from_element },
  38. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "element", ":element_id", "elements" }, &Client::handle_find_elements_from_element },
  39. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "element", ":element_id", "attribute", ":name" }, &Client::handle_get_element_attribute },
  40. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "cookie" }, &Client::handle_get_all_cookies },
  41. { HTTP::HttpRequest::Method::GET, { "session", ":session_id", "cookie", ":name" }, &Client::handle_get_named_cookie },
  42. { HTTP::HttpRequest::Method::POST, { "session", ":session_id", "cookie" }, &Client::handle_add_cookie },
  43. { HTTP::HttpRequest::Method::DELETE, { "session", ":session_id", "cookie", ":name" }, &Client::handle_delete_cookie },
  44. { HTTP::HttpRequest::Method::DELETE, { "session", ":session_id", "cookie" }, &Client::handle_delete_all_cookies },
  45. };
  46. Client::Client(NonnullOwnPtr<Core::Stream::BufferedTCPSocket> socket, Core::Object* parent)
  47. : Core::Object(parent)
  48. , m_socket(move(socket))
  49. {
  50. }
  51. void Client::die()
  52. {
  53. m_socket->close();
  54. deferred_invoke([this] { remove_from_parent(); });
  55. }
  56. void Client::start()
  57. {
  58. m_socket->on_ready_to_read = [this] {
  59. StringBuilder builder;
  60. // FIXME: All this should be moved to LibHTTP and be made spec compliant
  61. auto maybe_buffer = ByteBuffer::create_uninitialized(m_socket->buffer_size());
  62. if (maybe_buffer.is_error()) {
  63. warnln("Could not create buffer for client: {}", maybe_buffer.error());
  64. die();
  65. return;
  66. }
  67. auto buffer = maybe_buffer.release_value();
  68. for (;;) {
  69. auto maybe_can_read = m_socket->can_read_without_blocking();
  70. if (maybe_can_read.is_error()) {
  71. warnln("Failed to get the blocking status for the socket: {}", maybe_can_read.error());
  72. die();
  73. return;
  74. }
  75. if (!maybe_can_read.value())
  76. break;
  77. auto maybe_data = m_socket->read(buffer);
  78. if (maybe_data.is_error()) {
  79. warnln("Failed to read data from the request: {}", maybe_data.error());
  80. die();
  81. return;
  82. }
  83. if (m_socket->is_eof()) {
  84. die();
  85. break;
  86. }
  87. builder.append(StringView(maybe_data.value()));
  88. }
  89. auto request = builder.to_byte_buffer();
  90. auto http_request_or_error = HTTP::HttpRequest::from_raw_request(request);
  91. if (!http_request_or_error.has_value())
  92. return;
  93. auto http_request = http_request_or_error.release_value();
  94. auto body_or_error = read_body_as_json(http_request);
  95. if (body_or_error.is_error()) {
  96. warnln("Failed to read the request body: {}", body_or_error.error());
  97. die();
  98. return;
  99. }
  100. auto maybe_did_handle = handle_request(http_request, body_or_error.value());
  101. if (maybe_did_handle.is_error()) {
  102. warnln("Failed to handle the request: {}", maybe_did_handle.error());
  103. }
  104. die();
  105. };
  106. }
  107. ErrorOr<JsonValue> Client::read_body_as_json(HTTP::HttpRequest const& request)
  108. {
  109. // If we received a multipart body here, this would fail badly.
  110. unsigned content_length = 0;
  111. for (auto const& header : request.headers()) {
  112. if (header.name.equals_ignoring_case("Content-Length"sv)) {
  113. content_length = header.value.to_int(TrimWhitespace::Yes).value_or(0);
  114. break;
  115. }
  116. }
  117. if (!content_length)
  118. return JsonValue();
  119. // FIXME: Check the Content-Type is actually application/json
  120. JsonParser json_parser(request.body());
  121. return json_parser.parse();
  122. }
  123. ErrorOr<bool> Client::handle_request(HTTP::HttpRequest const& request, JsonValue const& body)
  124. {
  125. if constexpr (WEBDRIVER_DEBUG) {
  126. dbgln("Got HTTP request: {} {}", request.method_name(), request.resource());
  127. if (!body.is_null())
  128. dbgln("Body: {}", body.to_string());
  129. }
  130. auto routing_result_match = match_route(request.method(), request.resource());
  131. if (routing_result_match.is_error()) {
  132. auto error = routing_result_match.release_error();
  133. dbgln_if(WEBDRIVER_DEBUG, "Failed to match route: {}", error);
  134. TRY(send_error_response(error, request));
  135. return false;
  136. }
  137. auto routing_result = routing_result_match.release_value();
  138. auto result = (this->*routing_result.handler)(routing_result.parameters, body);
  139. if (result.is_error()) {
  140. dbgln_if(WEBDRIVER_DEBUG, "Error in calling route handler: {}", result.error());
  141. TRY(send_error_response(result.release_error(), request));
  142. return false;
  143. }
  144. auto object = result.release_value();
  145. TRY(send_response(object.to_string(), request));
  146. return true;
  147. }
  148. // https://w3c.github.io/webdriver/#dfn-send-a-response
  149. ErrorOr<void> Client::send_response(StringView content, HTTP::HttpRequest const& request)
  150. {
  151. // FIXME: Implement to spec.
  152. StringBuilder builder;
  153. builder.append("HTTP/1.0 200 OK\r\n"sv);
  154. builder.append("Server: WebDriver (SerenityOS)\r\n"sv);
  155. builder.append("X-Frame-Options: SAMEORIGIN\r\n"sv);
  156. builder.append("X-Content-Type-Options: nosniff\r\n"sv);
  157. builder.append("Pragma: no-cache\r\n"sv);
  158. builder.append("Content-Type: application/json; charset=utf-8\r\n"sv);
  159. builder.appendff("Content-Length: {}\r\n", content.length());
  160. builder.append("\r\n"sv);
  161. auto builder_contents = builder.to_byte_buffer();
  162. TRY(m_socket->write(builder_contents));
  163. TRY(m_socket->write(content.bytes()));
  164. log_response(200, request);
  165. auto keep_alive = false;
  166. if (auto it = request.headers().find_if([](auto& header) { return header.name.equals_ignoring_case("Connection"sv); }); !it.is_end()) {
  167. if (it->value.trim_whitespace().equals_ignoring_case("keep-alive"sv))
  168. keep_alive = true;
  169. }
  170. if (!keep_alive)
  171. m_socket->close();
  172. return {};
  173. }
  174. // https://w3c.github.io/webdriver/#dfn-send-an-error
  175. ErrorOr<void> Client::send_error_response(HttpError const& error, HTTP::HttpRequest const& request)
  176. {
  177. // FIXME: Implement to spec.
  178. dbgln("send_error_response: {} {}: {}", error.http_status, error.error, error.message);
  179. auto reason_phrase = HTTP::HttpResponse::reason_phrase_for_code(error.http_status);
  180. auto result = JsonObject();
  181. result.set("error", error.error);
  182. result.set("message", error.message);
  183. result.set("stacktrace", "");
  184. StringBuilder content_builder;
  185. result.serialize(content_builder);
  186. StringBuilder header_builder;
  187. header_builder.appendff("HTTP/1.0 {} ", error.http_status);
  188. header_builder.append(reason_phrase);
  189. header_builder.append("\r\n"sv);
  190. header_builder.append("Content-Type: application/json; charset=UTF-8\r\n"sv);
  191. header_builder.appendff("Content-Length: {}\r\n", content_builder.length());
  192. header_builder.append("\r\n"sv);
  193. TRY(m_socket->write(header_builder.to_byte_buffer()));
  194. TRY(m_socket->write(content_builder.to_byte_buffer()));
  195. log_response(error.http_status, request);
  196. return {};
  197. }
  198. void Client::log_response(unsigned code, HTTP::HttpRequest const& request)
  199. {
  200. outln("{} :: {:03d} :: {} {}", Core::DateTime::now().to_string(), code, request.method_name(), request.resource());
  201. }
  202. // https://w3c.github.io/webdriver/#dfn-match-a-request
  203. ErrorOr<Client::RoutingResult, HttpError> Client::match_route(HTTP::HttpRequest::Method method, String const& resource)
  204. {
  205. // FIXME: Implement to spec.
  206. dbgln_if(WEBDRIVER_DEBUG, "match_route({}, {})", HTTP::to_string(method), resource);
  207. // https://w3c.github.io/webdriver/webdriver-spec.html#routing-requests
  208. if (!resource.starts_with(m_prefix))
  209. return HttpError { 404, "unknown command", "The resource doesn't start with the prefix." };
  210. Vector<StringView> resource_split = resource.substring_view(m_prefix.length()).split_view('/', true);
  211. Vector<StringView> parameters;
  212. bool matched_path = false;
  213. for (auto const& route : Client::s_routes) {
  214. dbgln_if(WEBDRIVER_DEBUG, "- Checking {} {}", HTTP::to_string(route.method), String::join("/"sv, route.path));
  215. if (resource_split.size() != route.path.size()) {
  216. dbgln_if(WEBDRIVER_DEBUG, "-> Discarding: Wrong length");
  217. continue;
  218. }
  219. bool match = true;
  220. for (size_t i = 0; i < route.path.size(); ++i) {
  221. if (route.path[i].starts_with(':')) {
  222. parameters.append(resource_split[i]);
  223. continue;
  224. }
  225. if (route.path[i] != resource_split[i]) {
  226. match = false;
  227. parameters.clear();
  228. dbgln_if(WEBDRIVER_DEBUG, "-> Discarding: Part `{}` does not match `{}`", route.path[i], resource_split[i]);
  229. break;
  230. }
  231. }
  232. if (match && route.method == method) {
  233. dbgln_if(WEBDRIVER_DEBUG, "-> Matched! :^)");
  234. return RoutingResult { route.handler, parameters };
  235. }
  236. matched_path = true;
  237. }
  238. // Matched a path, but didn't match a known method
  239. if (matched_path) {
  240. dbgln_if(WEBDRIVER_DEBUG, "- A path matched, but method didn't. :^(");
  241. return HttpError { 405, "unknown method", "The command matched a known URL but did not match a method for that URL." };
  242. }
  243. // Didn't have any match
  244. dbgln_if(WEBDRIVER_DEBUG, "- No matches. :^(");
  245. return HttpError { 404, "unknown command", "The command was not recognized." };
  246. }
  247. ErrorOr<Session*, HttpError> Client::find_session_with_id(StringView session_id)
  248. {
  249. auto session_id_or_error = session_id.to_uint<>();
  250. if (!session_id_or_error.has_value())
  251. return HttpError { 404, "invalid session id", "Invalid session id" };
  252. for (auto& session : Client::s_sessions) {
  253. if (session.session_id() == session_id_or_error.value())
  254. return &session;
  255. }
  256. return HttpError { 404, "invalid session id", "Invalid session id" };
  257. }
  258. void Client::close_session(unsigned session_id)
  259. {
  260. bool found = Client::s_sessions.remove_first_matching([&](auto const& it) {
  261. return it->session_id() == session_id;
  262. });
  263. if (found)
  264. dbgln_if(WEBDRIVER_DEBUG, "Shut down session {}", session_id);
  265. else
  266. dbgln_if(WEBDRIVER_DEBUG, "Unable to shut down session {}: Not found", session_id);
  267. }
  268. JsonValue Client::make_json_value(JsonValue const& value)
  269. {
  270. JsonObject result;
  271. result.set("value", value);
  272. return result;
  273. }
  274. // 8.1 New Session, https://w3c.github.io/webdriver/#dfn-new-sessions
  275. // POST /session
  276. ErrorOr<JsonValue, HttpError> Client::handle_new_session(Vector<StringView> const&, JsonValue const&)
  277. {
  278. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session");
  279. // FIXME: 1. If the maximum active sessions is equal to the length of the list of active sessions,
  280. // return error with error code session not created.
  281. // FIXME: 2. If the remote end is an intermediary node, take implementation-defined steps that either
  282. // result in returning an error with error code session not created, or in returning a
  283. // success with data that is isomorphic to that returned by remote ends according to the
  284. // rest of this algorithm. If an error is not returned, the intermediary node must retain a
  285. // reference to the session created on the upstream node as the associated session such
  286. // that commands may be forwarded to this associated session on subsequent commands.
  287. // FIXME: 3. If the maximum active sessions is equal to the length of the list of active sessions,
  288. // return error with error code session not created.
  289. // FIXME: 4. Let capabilities be the result of trying to process capabilities with parameters as an argument.
  290. auto capabilities = JsonObject {};
  291. // FIXME: 5. If capabilities’s is null, return error with error code session not created.
  292. // 6. Let session id be the result of generating a UUID.
  293. // FIXME: Actually create a UUID.
  294. auto session_id = Client::s_next_session_id++;
  295. // 7. Let session be a new session with the session ID of session id.
  296. NonnullOwnPtr<Session> session = make<Session>(session_id, *this);
  297. auto start_result = session->start();
  298. if (start_result.is_error()) {
  299. return HttpError { 500, "Failed to start session", start_result.error().string_literal() };
  300. }
  301. // FIXME: 8. Set the current session to session.
  302. // FIXME: 9. Run any WebDriver new session algorithm defined in external specifications,
  303. // with arguments session and capabilities.
  304. // 10. Append session to active sessions.
  305. Client::s_sessions.append(move(session));
  306. // 11. Let body be a JSON Object initialized with:
  307. JsonObject body;
  308. // "sessionId"
  309. // session id
  310. body.set("sessionId", String::number(session_id));
  311. // "capabilities"
  312. // capabilities
  313. body.set("capabilities", move(capabilities));
  314. // FIXME: 12. Initialize the following from capabilities:
  315. // NOTE: See spec for steps
  316. // FIXME: 13. Set the webdriver-active flag to true.
  317. // FIXME: 14. Set the current top-level browsing context for session with the top-level browsing context
  318. // of the UA’s current browsing context.
  319. // FIXME: 15. Set the request queue to a new queue.
  320. // 16. Return success with data body.
  321. return make_json_value(body);
  322. }
  323. // 8.2 Delete Session, https://w3c.github.io/webdriver/#dfn-delete-session
  324. // DELETE /session/{session id}
  325. ErrorOr<JsonValue, HttpError> Client::handle_delete_session(Vector<StringView> const& parameters, JsonValue const&)
  326. {
  327. dbgln_if(WEBDRIVER_DEBUG, "Handling DELETE /session/<session_id>");
  328. // 1. If the current session is an active session, try to close the session.
  329. auto* session = TRY(find_session_with_id(parameters[0]));
  330. auto stop_result = session->stop();
  331. if (stop_result.is_error()) {
  332. return HttpError { 500, "unsupported operation", stop_result.error().string_literal() };
  333. }
  334. // 2. Return success with data null.
  335. return make_json_value(JsonValue());
  336. }
  337. // 8.3 Status, https://w3c.github.io/webdriver/#dfn-status
  338. // GET /status
  339. ErrorOr<JsonValue, HttpError> Client::handle_get_status(Vector<StringView> const&, JsonValue const&)
  340. {
  341. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /status");
  342. // 1. Let body be a new JSON Object with the following properties:
  343. // "ready"
  344. // The remote end’s readiness state.
  345. // "message"
  346. // An implementation-defined string explaining the remote end’s readiness state.
  347. // FIXME: Report if we are somehow not ready.
  348. JsonObject body;
  349. body.set("ready", true);
  350. body.set("message", "Ready to start some sessions!");
  351. // 2. Return success with data body.
  352. return body;
  353. }
  354. // 9.1 Get Timeouts, https://w3c.github.io/webdriver/#dfn-get-timeouts
  355. // GET /session/{session id}/timeouts
  356. ErrorOr<JsonValue, HttpError> Client::handle_get_timeouts(Vector<AK::StringView> const& parameters, AK::JsonValue const&)
  357. {
  358. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session id>/timeouts");
  359. auto* session = TRY(find_session_with_id(parameters[0]));
  360. // NOTE: Spec steps handled in Session::get_timeouts().
  361. auto result = session->get_timeouts();
  362. return make_json_value(result);
  363. }
  364. // 9.2 Set Timeouts, https://w3c.github.io/webdriver/#dfn-set-timeouts
  365. // POST /session/{session id}/timeouts
  366. ErrorOr<JsonValue, HttpError> Client::handle_set_timeouts(Vector<AK::StringView> const& parameters, AK::JsonValue const& payload)
  367. {
  368. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session id>/timeouts");
  369. auto* session = TRY(find_session_with_id(parameters[0]));
  370. // NOTE: Spec steps handled in Session::set_timeouts().
  371. auto result = TRY(session->set_timeouts(payload));
  372. return make_json_value(result);
  373. }
  374. // 10.1 Navigate To, https://w3c.github.io/webdriver/#dfn-navigate-to
  375. // POST /session/{session id}/url
  376. ErrorOr<JsonValue, HttpError> Client::handle_navigate_to(Vector<StringView> const& parameters, JsonValue const& payload)
  377. {
  378. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/url");
  379. auto* session = TRY(find_session_with_id(parameters[0]));
  380. // NOTE: Spec steps handled in Session::navigate_to().
  381. auto result = TRY(session->navigate_to(payload));
  382. return make_json_value(result);
  383. }
  384. // 10.2 Get Current URL, https://w3c.github.io/webdriver/#dfn-get-current-url
  385. // GET /session/{session id}/url
  386. ErrorOr<JsonValue, HttpError> Client::handle_get_current_url(Vector<StringView> const& parameters, JsonValue const&)
  387. {
  388. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/url");
  389. auto* session = TRY(find_session_with_id(parameters[0]));
  390. // NOTE: Spec steps handled in Session::get_current_url().
  391. auto result = TRY(session->get_current_url());
  392. return make_json_value(result);
  393. }
  394. // 10.3 Back, https://w3c.github.io/webdriver/#dfn-back
  395. // POST /session/{session id}/back
  396. ErrorOr<JsonValue, HttpError> Client::handle_back(Vector<StringView> const& parameters, JsonValue const&)
  397. {
  398. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/back");
  399. auto* session = TRY(find_session_with_id(parameters[0]));
  400. // NOTE: Spec steps handled in Session::back().
  401. auto result = TRY(session->back());
  402. return make_json_value(result);
  403. }
  404. // 10.4 Forward, https://w3c.github.io/webdriver/#dfn-forward
  405. // POST /session/{session id}/forward
  406. ErrorOr<JsonValue, HttpError> Client::handle_forward(Vector<StringView> const& parameters, JsonValue const&)
  407. {
  408. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/forward");
  409. auto* session = TRY(find_session_with_id(parameters[0]));
  410. // NOTE: Spec steps handled in Session::forward().
  411. auto result = TRY(session->forward());
  412. return make_json_value(result);
  413. }
  414. // 10.5 Refresh, https://w3c.github.io/webdriver/#dfn-refresh
  415. // POST /session/{session id}/refresh
  416. ErrorOr<JsonValue, HttpError> Client::handle_refresh(Vector<StringView> const& parameters, JsonValue const&)
  417. {
  418. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/refresh");
  419. auto* session = TRY(find_session_with_id(parameters[0]));
  420. // NOTE: Spec steps handled in Session::refresh().
  421. auto result = TRY(session->refresh());
  422. return make_json_value(result);
  423. }
  424. // 10.6 Get Title, https://w3c.github.io/webdriver/#dfn-get-title
  425. // GET /session/{session id}/title
  426. ErrorOr<JsonValue, HttpError> Client::handle_get_title(Vector<StringView> const& parameters, JsonValue const&)
  427. {
  428. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/title");
  429. auto* session = TRY(find_session_with_id(parameters[0]));
  430. // NOTE: Spec steps handled in Session::get_title().
  431. auto result = TRY(session->get_title());
  432. return make_json_value(result);
  433. }
  434. // 11.1 Get Window Handle, https://w3c.github.io/webdriver/#get-window-handle
  435. // GET /session/{session id}/window
  436. ErrorOr<JsonValue, HttpError> Client::handle_get_window_handle(Vector<StringView> const& parameters, JsonValue const&)
  437. {
  438. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/window");
  439. auto* session = TRY(find_session_with_id(parameters[0]));
  440. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  441. auto current_window = session->get_window_object();
  442. if (!current_window.has_value())
  443. return HttpError { 404, "no such window", "Window not found" };
  444. // 2. Return success with data being the window handle associated with the current top-level browsing context.
  445. return make_json_value(session->current_window_handle());
  446. }
  447. // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window
  448. // DELETE /session/{session id}/window
  449. ErrorOr<JsonValue, HttpError> Client::handle_close_window(Vector<StringView> const& parameters, JsonValue const&)
  450. {
  451. dbgln_if(WEBDRIVER_DEBUG, "Handling DELETE /session/<session_id>/window");
  452. auto* session = TRY(find_session_with_id(parameters[0]));
  453. // NOTE: Spec steps handled in Session::close_window().
  454. TRY(unwrap_result(session->close_window()));
  455. return make_json_value(JsonValue());
  456. }
  457. // 12.3.2 Find Element, https://w3c.github.io/webdriver/#dfn-find-element
  458. // POST /session/{session id}/element
  459. ErrorOr<JsonValue, HttpError> Client::handle_find_element(Vector<StringView> const& parameters, JsonValue const& payload)
  460. {
  461. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/element");
  462. auto* session = TRY(find_session_with_id(parameters[0]));
  463. // NOTE: Spec steps handled in Session::find_element().
  464. auto result = TRY(session->find_element(payload));
  465. return make_json_value(result);
  466. }
  467. // 12.3.3 Find Elements, https://w3c.github.io/webdriver/#dfn-find-elements
  468. // POST /session/{session id}/elements
  469. ErrorOr<JsonValue, HttpError> Client::handle_find_elements(Vector<StringView> const& parameters, JsonValue const& payload)
  470. {
  471. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/elements");
  472. auto* session = TRY(find_session_with_id(parameters[0]));
  473. // NOTE: Spec steps handled in Session::find_elements().
  474. auto result = TRY(session->find_elements(payload));
  475. return make_json_value(result);
  476. }
  477. // 12.3.4 Find Element From Element, https://w3c.github.io/webdriver/#dfn-find-element-from-element
  478. // POST /session/{session id}/element/{element id}/element
  479. ErrorOr<JsonValue, HttpError> Client::handle_find_element_from_element(Vector<StringView> const& parameters, JsonValue const& payload)
  480. {
  481. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/element/<element_id>/element");
  482. auto* session = TRY(find_session_with_id(parameters[0]));
  483. // NOTE: Spec steps handled in Session::find_element_from_element().
  484. auto result = TRY(session->find_element_from_element(payload, parameters[1]));
  485. return make_json_value(result);
  486. }
  487. // 12.3.5 Find Elements From Element, https://w3c.github.io/webdriver/#dfn-find-elements-from-element
  488. // POST /session/{session id}/element/{element id}/elements
  489. ErrorOr<JsonValue, HttpError> Client::handle_find_elements_from_element(Vector<StringView> const& parameters, JsonValue const& payload)
  490. {
  491. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/element/<element_id>/elements");
  492. auto* session = TRY(find_session_with_id(parameters[0]));
  493. // NOTE: Spec steps handled in Session::find_elements_from_element().
  494. auto result = TRY(session->find_elements_from_element(payload, parameters[1]));
  495. return make_json_value(result);
  496. }
  497. // 12.4.2 Get Element Attribute, https://w3c.github.io/webdriver/#dfn-get-element-attribute
  498. // GET /session/{session id}/element/{element id}/attribute/{name}
  499. ErrorOr<JsonValue, HttpError> Client::handle_get_element_attribute(Vector<StringView> const& parameters, JsonValue const& payload)
  500. {
  501. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/element/<element_id>/attribute/<name>");
  502. auto* session = TRY(find_session_with_id(parameters[0]));
  503. // NOTE: Spec steps handled in Session::get_element_attribute().
  504. auto result = TRY(session->get_element_attribute(payload, parameters[1], parameters[2]));
  505. return make_json_value(result);
  506. }
  507. // 14.1 Get All Cookies, https://w3c.github.io/webdriver/#dfn-get-all-cookies
  508. // GET /session/{session id}/cookie
  509. ErrorOr<JsonValue, HttpError> Client::handle_get_all_cookies(Vector<StringView> const& parameters, JsonValue const&)
  510. {
  511. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/cookie");
  512. auto* session = TRY(find_session_with_id(parameters[0]));
  513. // NOTE: Spec steps handled in Session::get_all_cookies().
  514. auto cookies = TRY(session->get_all_cookies());
  515. return make_json_value(cookies);
  516. }
  517. // 14.2 Get Named Cookie, https://w3c.github.io/webdriver/#dfn-get-named-cookie
  518. // GET /session/{session id}/cookie/{name}
  519. ErrorOr<JsonValue, HttpError> Client::handle_get_named_cookie(Vector<StringView> const& parameters, JsonValue const&)
  520. {
  521. dbgln_if(WEBDRIVER_DEBUG, "Handling GET /session/<session_id>/cookie/<name>");
  522. auto* session = TRY(find_session_with_id(parameters[0]));
  523. // NOTE: Spec steps handled in Session::get_all_cookies().
  524. auto cookies = TRY(session->get_named_cookie(parameters[1]));
  525. return make_json_value(cookies);
  526. }
  527. // 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
  528. // POST /session/{session id}/cookie
  529. ErrorOr<JsonValue, HttpError> Client::handle_add_cookie(Vector<StringView> const& parameters, JsonValue const& payload)
  530. {
  531. dbgln_if(WEBDRIVER_DEBUG, "Handling POST /session/<session_id>/cookie");
  532. auto* session = TRY(find_session_with_id(parameters[0]));
  533. // NOTE: Spec steps handled in Session::add_cookie().
  534. auto result = TRY(session->add_cookie(payload));
  535. return make_json_value(result);
  536. }
  537. // 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
  538. // DELETE /session/{session id}/cookie/{name}
  539. ErrorOr<JsonValue, HttpError> Client::handle_delete_cookie(Vector<StringView> const& parameters, JsonValue const&)
  540. {
  541. dbgln_if(WEBDRIVER_DEBUG, "Handling DELETE /session/<session_id>/cookie/<name>");
  542. auto* session = TRY(find_session_with_id(parameters[0]));
  543. // NOTE: Spec steps handled in Session::delete_cookie().
  544. auto result = TRY(session->delete_cookie(parameters[1]));
  545. return make_json_value(result);
  546. }
  547. // 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
  548. // DELETE /session/{session id}/cookie
  549. ErrorOr<JsonValue, HttpError> Client::handle_delete_all_cookies(Vector<StringView> const& parameters, JsonValue const&)
  550. {
  551. dbgln_if(WEBDRIVER_DEBUG, "Handling DELETE /session/<session_id>/cookie");
  552. auto* session = TRY(find_session_with_id(parameters[0]));
  553. // NOTE: Spec steps handled in Session::delete_all_cookies().
  554. auto result = TRY(session->delete_all_cookies());
  555. return make_json_value(result);
  556. }
  557. }