forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebDriverService.cpp
2714 lines (2338 loc) · 111 KB
/
WebDriverService.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2017 Igalia S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebDriverService.h"
#include "Capabilities.h"
#include "CommandResult.h"
#include "SessionHost.h"
#include <wtf/Compiler.h>
#include <wtf/LoggerHelper.h>
#include <wtf/RunLoop.h>
#include <wtf/SortedArrayMap.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringToIntegerConversion.h>
#include <wtf/text/WTFString.h>
#if ENABLE(WEBDRIVER_BIDI)
#include "HTTPServer.h"
#include "WebSocketServer.h"
#include <algorithm>
#include <array>
#include <cstdio>
#include <optional>
#include <wtf/JSONValues.h>
#include <wtf/StdLibExtras.h>
#include <wtf/glib/GTypedefs.h>
#endif
namespace WebDriver {
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-maximum-safe-integer
static const double maxSafeInteger = 9007199254740991.0; // 2 ^ 53 - 1
WebDriverService::WebDriverService()
: m_server(*this)
#if ENABLE(WEBDRIVER_BIDI)
, m_bidiServer(*this, *this)
, m_browserTerminatedObserver([this](const String& sessionID) { onBrowserTerminated(sessionID); })
#endif
{
#if ENABLE(WEBDRIVER_BIDI)
SessionHost::addBrowserTerminatedObserver(m_browserTerminatedObserver);
#endif
}
WebDriverService::~WebDriverService()
{
#if ENABLE(WEBDRIVER_BIDI)
SessionHost::removeBrowserTerminatedObserver(m_browserTerminatedObserver);
#endif
}
static void printUsageStatement(const char* programName)
{
printf("Usage: %s options\n", programName);
printf(" -h, --help Prints this help message\n");
printf(" -p <port>, --port=<port> Port number the driver will use\n");
printf(" --host=<host> Host IP the driver will use, or either 'local' or 'all' (default: 'local')\n");
printf(" -t <ip:port> --target=<ip:port> Target IP and port\n");
#if ENABLE(WEBDRIVER_BIDI)
printf(" --bidi-port=<port> Port number to use for BiDi's WebSocket connections\n");
#endif
}
int WebDriverService::run(int argc, char** argv)
{
String portString;
std::optional<String> host;
#if ENABLE(WEBDRIVER_BIDI)
String bidiPortString;
#endif
String targetString;
if (const char* targetEnvVar = getenv("WEBDRIVER_TARGET_ADDR"))
targetString = String::fromLatin1(targetEnvVar);
for (int i = 1 ; i < argc; ++i) {
const char* arg = argv[i];
if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) {
printUsageStatement(argv[0]);
return EXIT_SUCCESS;
}
if (!strcmp(arg, "-p") && portString.isNull()) {
if (++i == argc) {
printUsageStatement(argv[0]);
return EXIT_FAILURE;
}
portString = String::fromLatin1(argv[i]);
continue;
}
static const unsigned portStrLength = strlen("--port=");
if (!strncmp(arg, "--port=", portStrLength) && portString.isNull()) {
portString = String::fromLatin1(arg + portStrLength);
continue;
}
static const unsigned hostStrLength = strlen("--host=");
if (!strncmp(arg, "--host=", hostStrLength) && !host) {
host = String::fromLatin1(arg + hostStrLength);
continue;
}
#if ENABLE(WEBDRIVER_BIDI)
static const unsigned bidiPortStrLength = strlen("--bidi-port=");
if (!strncmp(arg, "--bidi-port=", bidiPortStrLength) && bidiPortString.isNull()) {
bidiPortString = String::fromLatin1(arg + bidiPortStrLength);
continue;
}
#endif
if (!strcmp(arg, "-t") && targetString.isNull()) {
if (++i == argc) {
printUsageStatement(argv[0]);
return EXIT_FAILURE;
}
targetString = String::fromLatin1(argv[i]);
continue;
}
static const unsigned targetStrLength = strlen("--target=");
if (!strncmp(arg, "--target=", targetStrLength) && targetString.isNull()) {
targetString = String::fromLatin1(arg + targetStrLength);
continue;
}
}
if (portString.isNull()) {
printUsageStatement(argv[0]);
return EXIT_FAILURE;
}
if (!targetString.isEmpty()) {
auto position = targetString.reverseFind(':');
if (position != notFound) {
m_targetAddress = targetString.left(position);
m_targetPort = parseIntegerAllowingTrailingJunk<uint16_t>(StringView { targetString }.substring(position + 1)).value_or(0);
}
}
auto port = parseInteger<uint16_t>(portString);
if (!port) {
fprintf(stderr, "Invalid port %s provided\n", portString.utf8().data());
return EXIT_FAILURE;
}
#if ENABLE(WEBDRIVER_BIDI)
auto bidiPort = parseInteger<uint16_t>(bidiPortString);
if (!bidiPort) {
fprintf(stderr, "Invalid WebSocket port %s provided. Defaulting to 4445.\n", bidiPortString.utf8().data());
bidiPort = { 4445 };
}
#endif
WTF::initializeMainThread();
#if ENABLE(WEBDRIVER_BIDI)
if (!m_bidiServer.listen(host ? *host : nullString(), *bidiPort))
return EXIT_FAILURE;
#endif // ENABLE(WEBDRIVER_BIDI)
if (!m_server.listen(host, *port))
return EXIT_FAILURE;
RunLoop::run();
#if ENABLE(WEBDRIVER_BIDI)
m_bidiServer.disconnect();
#endif
m_server.disconnect();
return EXIT_SUCCESS;
}
const WebDriverService::Command WebDriverService::s_commands[] = {
{ HTTPMethod::Post, "/session", &WebDriverService::newSession },
{ HTTPMethod::Delete, "/session/$sessionId", &WebDriverService::deleteSession },
{ HTTPMethod::Get, "/status", &WebDriverService::status },
{ HTTPMethod::Get, "/session/$sessionId/timeouts", &WebDriverService::getTimeouts },
{ HTTPMethod::Post, "/session/$sessionId/timeouts", &WebDriverService::setTimeouts },
{ HTTPMethod::Post, "/session/$sessionId/url", &WebDriverService::go },
{ HTTPMethod::Get, "/session/$sessionId/url", &WebDriverService::getCurrentURL },
{ HTTPMethod::Post, "/session/$sessionId/back", &WebDriverService::back },
{ HTTPMethod::Post, "/session/$sessionId/forward", &WebDriverService::forward },
{ HTTPMethod::Post, "/session/$sessionId/refresh", &WebDriverService::refresh },
{ HTTPMethod::Get, "/session/$sessionId/title", &WebDriverService::getTitle },
{ HTTPMethod::Get, "/session/$sessionId/window", &WebDriverService::getWindowHandle },
{ HTTPMethod::Delete, "/session/$sessionId/window", &WebDriverService::closeWindow },
{ HTTPMethod::Post, "/session/$sessionId/window", &WebDriverService::switchToWindow },
{ HTTPMethod::Get, "/session/$sessionId/window/handles", &WebDriverService::getWindowHandles },
{ HTTPMethod::Post, "/session/$sessionId/window/new", &WebDriverService::newWindow },
{ HTTPMethod::Post, "/session/$sessionId/frame", &WebDriverService::switchToFrame },
{ HTTPMethod::Post, "/session/$sessionId/frame/parent", &WebDriverService::switchToParentFrame },
{ HTTPMethod::Get, "/session/$sessionId/window/rect", &WebDriverService::getWindowRect },
{ HTTPMethod::Post, "/session/$sessionId/window/rect", &WebDriverService::setWindowRect },
{ HTTPMethod::Post, "/session/$sessionId/window/maximize", &WebDriverService::maximizeWindow },
{ HTTPMethod::Post, "/session/$sessionId/window/minimize", &WebDriverService::minimizeWindow },
{ HTTPMethod::Post, "/session/$sessionId/window/fullscreen", &WebDriverService::fullscreenWindow },
{ HTTPMethod::Post, "/session/$sessionId/element", &WebDriverService::findElement },
{ HTTPMethod::Post, "/session/$sessionId/elements", &WebDriverService::findElements },
{ HTTPMethod::Post, "/session/$sessionId/element/$elementId/element", &WebDriverService::findElementFromElement },
{ HTTPMethod::Post, "/session/$sessionId/element/$elementId/elements", &WebDriverService::findElementsFromElement },
{ HTTPMethod::Post, "/session/$sessionId/shadow/$shadowId/element", &WebDriverService::findElementFromShadowRoot },
{ HTTPMethod::Post, "/session/$sessionId/shadow/$shadowId/elements", &WebDriverService::findElementsFromShadowRoot },
{ HTTPMethod::Get, "/session/$sessionId/element/active", &WebDriverService::getActiveElement },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/shadow", &WebDriverService::getElementShadowRoot },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/selected", &WebDriverService::isElementSelected },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/attribute/$name", &WebDriverService::getElementAttribute },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/property/$name", &WebDriverService::getElementProperty },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/css/$name", &WebDriverService::getElementCSSValue },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/text", &WebDriverService::getElementText },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/name", &WebDriverService::getElementTagName },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/rect", &WebDriverService::getElementRect },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/enabled", &WebDriverService::isElementEnabled },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/computedrole", &WebDriverService::getComputedRole },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/computedlabel", &WebDriverService::getComputedLabel },
{ HTTPMethod::Post, "/session/$sessionId/element/$elementId/click", &WebDriverService::elementClick },
{ HTTPMethod::Post, "/session/$sessionId/element/$elementId/clear", &WebDriverService::elementClear },
{ HTTPMethod::Post, "/session/$sessionId/element/$elementId/value", &WebDriverService::elementSendKeys },
{ HTTPMethod::Get, "/session/$sessionId/source", &WebDriverService::getPageSource },
{ HTTPMethod::Post, "/session/$sessionId/execute/sync", &WebDriverService::executeScript },
{ HTTPMethod::Post, "/session/$sessionId/execute/async", &WebDriverService::executeAsyncScript },
{ HTTPMethod::Get, "/session/$sessionId/cookie", &WebDriverService::getAllCookies },
{ HTTPMethod::Get, "/session/$sessionId/cookie/$name", &WebDriverService::getNamedCookie },
{ HTTPMethod::Post, "/session/$sessionId/cookie", &WebDriverService::addCookie },
{ HTTPMethod::Delete, "/session/$sessionId/cookie/$name", &WebDriverService::deleteCookie },
{ HTTPMethod::Delete, "/session/$sessionId/cookie", &WebDriverService::deleteAllCookies },
{ HTTPMethod::Post, "/session/$sessionId/actions", &WebDriverService::performActions },
{ HTTPMethod::Delete, "/session/$sessionId/actions", &WebDriverService::releaseActions },
{ HTTPMethod::Post, "/session/$sessionId/alert/dismiss", &WebDriverService::dismissAlert },
{ HTTPMethod::Post, "/session/$sessionId/alert/accept", &WebDriverService::acceptAlert },
{ HTTPMethod::Get, "/session/$sessionId/alert/text", &WebDriverService::getAlertText },
{ HTTPMethod::Post, "/session/$sessionId/alert/text", &WebDriverService::sendAlertText },
{ HTTPMethod::Get, "/session/$sessionId/screenshot", &WebDriverService::takeScreenshot },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/screenshot", &WebDriverService::takeElementScreenshot },
{ HTTPMethod::Get, "/session/$sessionId/element/$elementId/displayed", &WebDriverService::isElementDisplayed },
};
#if ENABLE(WEBDRIVER_BIDI)
const WebDriverService::BidiCommand WebDriverService::s_bidiCommands[] = {
{ "session.status"_s, &WebDriverService::bidiSessionStatus },
};
#endif
std::optional<WebDriverService::HTTPMethod> WebDriverService::toCommandHTTPMethod(const String& method)
{
static constexpr std::pair<ComparableLettersLiteral, WebDriverService::HTTPMethod> httpMethodMappings[] = {
{ "delete"_s, WebDriverService::HTTPMethod::Delete },
{ "get"_s, WebDriverService::HTTPMethod::Get },
{ "post"_s, WebDriverService::HTTPMethod::Post },
{ "put"_s, WebDriverService::HTTPMethod::Post },
};
static constexpr SortedArrayMap httpMethods { httpMethodMappings };
if (auto* methodValue = httpMethods.tryGet(method))
return *methodValue;
return std::nullopt;
}
bool WebDriverService::findCommand(HTTPMethod method, const String& path, CommandHandler* handler, HashMap<String, String>& parameters)
{
size_t length = std::size(s_commands);
for (size_t i = 0; i < length; ++i) {
if (s_commands[i].method != method)
continue;
Vector<String> pathTokens = path.split('/');
Vector<String> commandTokens = String::fromUTF8(s_commands[i].uriTemplate).split('/');
if (pathTokens.size() != commandTokens.size())
continue;
bool allMatched = true;
for (size_t j = 0; j < pathTokens.size() && allMatched; ++j) {
if (commandTokens[j][0] == '$')
parameters.set(commandTokens[j].substring(1), pathTokens[j]);
else if (commandTokens[j] != pathTokens[j])
allMatched = false;
}
if (allMatched) {
*handler = s_commands[i].handler;
return true;
}
parameters.clear();
}
return false;
}
void WebDriverService::handleRequest(HTTPRequestHandler::Request&& request, Function<void (HTTPRequestHandler::Response&&)>&& replyHandler)
{
auto method = toCommandHTTPMethod(request.method);
if (!method) {
sendResponse(WTFMove(replyHandler), CommandResult::fail(CommandResult::ErrorCode::UnknownCommand, makeString("Unknown method: "_s, request.method)));
return;
}
CommandHandler handler;
HashMap<String, String> parameters;
if (!findCommand(method.value(), request.path, &handler, parameters)) {
sendResponse(WTFMove(replyHandler), CommandResult::fail(CommandResult::ErrorCode::UnknownCommand, makeString("Unknown command: "_s, request.path)));
return;
}
RefPtr<JSON::Object> parametersObject;
if (method.value() == HTTPMethod::Post) {
auto messageValue = JSON::Value::parseJSON(String::fromUTF8({ request.data, request.dataLength }));
if (!messageValue) {
sendResponse(WTFMove(replyHandler), CommandResult::fail(CommandResult::ErrorCode::InvalidArgument));
return;
}
parametersObject = messageValue->asObject();
if (!parametersObject) {
sendResponse(WTFMove(replyHandler), CommandResult::fail(CommandResult::ErrorCode::InvalidArgument));
return;
}
} else
parametersObject = JSON::Object::create();
for (const auto& parameter : parameters)
parametersObject->setString(parameter.key, parameter.value);
((*this).*handler)(WTFMove(parametersObject), [this, replyHandler = WTFMove(replyHandler)](CommandResult&& result) mutable {
sendResponse(WTFMove(replyHandler), WTFMove(result));
});
}
void WebDriverService::sendResponse(Function<void (HTTPRequestHandler::Response&&)>&& replyHandler, CommandResult&& result) const
{
// §6.3 Processing Model.
// https://w3c.github.io/webdriver/webdriver-spec.html#processing-model
RefPtr<JSON::Value> resultValue;
if (result.isError()) {
// When required to send an error.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-send-an-error
// Let body be a new JSON Object initialised with the following properties: "error", "message", "stacktrace".
auto errorObject = JSON::Object::create();
errorObject->setString("error"_s, result.errorString());
errorObject->setString("message"_s, result.errorMessage().value_or(emptyString()));
errorObject->setString("stacktrace"_s, emptyString());
// If the error data dictionary contains any entries, set the "data" field on body to a new JSON Object populated with the dictionary.
if (auto& additionalData = result.additionalErrorData())
errorObject->setObject("data"_s, *additionalData);
// Send a response with status and body as arguments.
resultValue = WTFMove(errorObject);
} else if (auto value = result.result())
resultValue = WTFMove(value);
else
resultValue = JSON::Value::null();
// When required to send a response.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-send-a-response
auto responseObject = JSON::Object::create();
responseObject->setValue("value"_s, resultValue.releaseNonNull());
replyHandler({ result.httpStatusCode(), responseObject->toJSONString().utf8(), "application/json; charset=utf-8"_s });
}
#if ENABLE(WEBDRIVER_BIDI)
bool WebDriverService::acceptHandshake(HTTPRequestHandler::Request&& request)
{
// https://w3c.github.io/webdriver-bidi/#transport
auto& resourceName = request.path;
auto& resources = m_bidiServer.listener()->resources;
auto foundResource = std::find(resources.begin(), resources.end(), resourceName);
if (foundResource == resources.end()) {
WTFLogAlways("Resource name %s not found in listener's list of WebSocket resources. Rejecting handshake.", resourceName.utf8().data());
return false;
}
if (*foundResource == "/session"_s) {
// FIXME Add support for bidi-only sessions
WTFLogAlways("BiDi-only sessions are not supported yet. Rejecting handshake.");
return false;
}
auto sessionID = m_bidiServer.getSessionID(resourceName);
if (sessionID.isNull()) {
WTFLogAlways("No session ID found for resource name %s. Rejecting handshake.", resourceName.utf8().data());
return false;
}
// FIXME Properly support multiple sessions in the future
if (sessionID != m_session->id()) {
WTFLogAlways("No active session found for session ID %s. Rejecting handshake.", sessionID.utf8().data());
return false;
}
return true;
}
void WebDriverService::handleMessage(WebSocketMessageHandler::Message&& message, Function<void(WebSocketMessageHandler::Message&&)>&& completionHandler)
{
// https://w3c.github.io/webdriver-bidi/#handle-an-incoming-message
if (!message.connection) {
WTFLogAlways("Incoming message without attached connection. Ignoring message.");
completionHandler(WebSocketMessageHandler::Message::fail(CommandResult::ErrorCode::UnknownError, std::nullopt));
return;
}
auto connection = message.connection;
auto session = m_bidiServer.session(connection);
if (!session) {
if (!m_bidiServer.isStaticConnection(connection)) {
WTFLogAlways("Unknown connection. Ignoring message.");
completionHandler(WebSocketMessageHandler::Message::fail(CommandResult::ErrorCode::InvalidSessionID, connection));
return;
}
}
// 6.6 If session is null and command is not a static command, then send an error response given connection, command id, and invalid session id, and return.
// FIXME support checking static vs non-static methods https://bugs.webkit.org/show_bug.cgi?id=281721
auto parsedMessageValue = JSON::Value::parseJSON(String::fromUTF8(message.payload.data()));
if (!parsedMessageValue) {
WTFLogAlways("WebDriver handle Message: Failed to parse incoming message");
completionHandler(WebSocketMessageHandler::Message::fail(CommandResult::ErrorCode::InvalidArgument, message.connection));
return;
}
if (session && m_session && session->id() != m_session->id()) {
WTFLogAlways("Not an active session. Ignoring message.");
return;
}
BidiCommandHandler handler;
unsigned id = 0;
RefPtr<JSON::Object> parameters;
if (!findBidiCommand(parsedMessageValue, &handler, id, parameters)) {
WTFLogAlways("Failed to find appropriate BiDi command");
std::optional<int> commandId;
if (auto parsedMessageObject = parsedMessageValue->asObject()) {
auto parsedCommandId = parsedMessageObject->getInteger("id"_s);
if (parsedCommandId && *parsedCommandId >= 0)
commandId = parsedCommandId;
}
auto errorCode = CommandResult::ErrorCode::UnknownCommand;
auto errorReply = WebSocketMessageHandler::Message::fail(errorCode, connection, { "Command not supported"_s }, commandId);
completionHandler(WTFMove(errorReply));
return;
}
((*this).*handler)(id, WTFMove(parameters), [completionHandler = WTFMove(completionHandler), message](WebSocketMessageHandler::Message&& resultMessage) {
// 6.7.5 If method is "session.new", let session be the entry in the list of active sessions whose session ID is equal to the "sessionId" property of value, append connection to session’s session WebSocket connections, and remove connection from the WebSocket connections not associated with a session.
// FIXME https://bugs.webkit.org/show_bug.cgi?id=281722
resultMessage.connection = message.connection;
completionHandler(WTFMove(resultMessage));
});
}
bool WebDriverService::findBidiCommand(RefPtr<JSON::Value>& parameters, BidiCommandHandler* handler, unsigned& id, RefPtr<JSON::Object>& parsedParams)
{
if (!parameters)
return false;
const auto& asObject = parameters->asObject();
if (!asObject)
return false;
std::optional<int> idOpt = asObject->getInteger("id"_s);
if (!idOpt)
return false;
const String& method = asObject->getString("method"_s);
if (!method)
return false;
auto candidate = std::find_if(std::begin(s_bidiCommands), std::end(s_bidiCommands),
[method](const BidiCommand& command) {
return method == command.method;
});
if (candidate == std::end(s_bidiCommands))
return false;
id = *idOpt;
parsedParams = asObject->getObject("params"_s);
*handler = candidate->handler;
return true;
}
#endif // ENABLE(WEBDRIVER_BIDI)
static std::optional<double> valueAsNumberInRange(const JSON::Value& value, double minAllowed = 0, double maxAllowed = std::numeric_limits<int>::max())
{
auto number = value.asDouble();
if (!number)
return std::nullopt;
if (std::isnan(*number) || std::isinf(*number))
return std::nullopt;
if (*number < minAllowed || *number > maxAllowed)
return std::nullopt;
return *number;
}
static std::optional<uint64_t> unsignedValue(JSON::Value& value)
{
auto number = valueAsNumberInRange(value, 0, maxSafeInteger);
if (!number)
return std::nullopt;
auto intValue = static_cast<uint64_t>(number.value());
// If the contained value is a double, bail in case it doesn't match the integer
// value, i.e. if the double value was not originally in integer form.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-integer
if (number.value() != intValue)
return std::nullopt;
return intValue;
}
enum class IgnoreUnknownTimeout : bool { No, Yes };
static std::optional<Timeouts> deserializeTimeouts(JSON::Object& timeoutsObject, IgnoreUnknownTimeout ignoreUnknownTimeout)
{
// §8.5 Set Timeouts.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-deserialize-as-a-timeout
Timeouts timeouts;
auto end = timeoutsObject.end();
for (auto it = timeoutsObject.begin(); it != end; ++it) {
if (it->key == "sessionId"_s)
continue;
if (it->key == "script"_s && it->value->isNull()) {
timeouts.script = std::numeric_limits<double>::infinity();
continue;
}
// If value is not an integer, or it is less than 0 or greater than the maximum safe integer, return error with error code invalid argument.
auto timeoutMS = unsignedValue(it->value);
if (!timeoutMS)
return std::nullopt;
if (it->key == "script"_s)
timeouts.script = timeoutMS.value();
else if (it->key == "pageLoad"_s)
timeouts.pageLoad = timeoutMS.value();
else if (it->key == "implicit"_s)
timeouts.implicit = timeoutMS.value();
else if (ignoreUnknownTimeout == IgnoreUnknownTimeout::No)
return std::nullopt;
}
return timeouts;
}
static std::optional<Proxy> deserializeProxy(JSON::Object& proxyObject)
{
// §7.1 Proxy.
// https://w3c.github.io/webdriver/#proxy
Proxy proxy;
proxy.type = proxyObject.getString("proxyType"_s);
if (!proxy.type)
return std::nullopt;
if (proxy.type == "direct"_s || proxy.type == "autodetect"_s || proxy.type == "system"_s)
return proxy;
if (proxy.type == "pac"_s) {
auto autoconfigURL = proxyObject.getString("proxyAutoconfigUrl"_s);
if (!autoconfigURL)
return std::nullopt;
proxy.autoconfigURL = URL({ }, autoconfigURL);
if (!proxy.autoconfigURL->isValid())
return std::nullopt;
return proxy;
}
if (proxy.type == "manual"_s) {
if (auto value = proxyObject.getValue("ftpProxy"_s)) {
auto ftpProxy = value->asString();
if (!ftpProxy)
return std::nullopt;
proxy.ftpURL = URL({ }, makeString("ftp://"_s, ftpProxy));
if (!proxy.ftpURL->isValid())
return std::nullopt;
}
if (auto value = proxyObject.getValue("httpProxy"_s)) {
auto httpProxy = value->asString();
if (!httpProxy)
return std::nullopt;
proxy.httpURL = URL({ }, makeString("http://"_s, httpProxy));
if (!proxy.httpURL->isValid())
return std::nullopt;
}
if (auto value = proxyObject.getValue("sslProxy"_s)) {
auto sslProxy = value->asString();
if (!sslProxy)
return std::nullopt;
proxy.httpsURL = URL({ }, makeString("https://"_s, sslProxy));
if (!proxy.httpsURL->isValid())
return std::nullopt;
}
if (auto value = proxyObject.getValue("socksProxy"_s)) {
auto socksProxy = value->asString();
if (!socksProxy)
return std::nullopt;
proxy.socksURL = URL({ }, makeString("socks://"_s, socksProxy));
if (!proxy.socksURL->isValid())
return std::nullopt;
auto socksVersionValue = proxyObject.getValue("socksVersion"_s);
if (!socksVersionValue)
return std::nullopt;
auto socksVersion = unsignedValue(*socksVersionValue);
if (!socksVersion || socksVersion.value() > 255)
return std::nullopt;
proxy.socksVersion = socksVersion.value();
}
if (auto value = proxyObject.getValue("noProxy"_s)) {
auto noProxy = value->asArray();
if (!noProxy)
return std::nullopt;
auto noProxyLength = noProxy->length();
for (unsigned i = 0; i < noProxyLength; ++i) {
auto address = noProxy->get(i)->asString();
if (!address)
return std::nullopt;
proxy.ignoreAddressList.append(address);
}
}
return proxy;
}
return std::nullopt;
}
static std::optional<PageLoadStrategy> deserializePageLoadStrategy(const String& pageLoadStrategy)
{
if (pageLoadStrategy == "none"_s)
return PageLoadStrategy::None;
if (pageLoadStrategy == "normal"_s)
return PageLoadStrategy::Normal;
if (pageLoadStrategy == "eager"_s)
return PageLoadStrategy::Eager;
return std::nullopt;
}
static std::optional<UnhandledPromptBehavior> deserializeUnhandledPromptBehavior(const String& unhandledPromptBehavior)
{
if (unhandledPromptBehavior == "dismiss"_s)
return UnhandledPromptBehavior::Dismiss;
if (unhandledPromptBehavior == "accept"_s)
return UnhandledPromptBehavior::Accept;
if (unhandledPromptBehavior == "dismiss and notify"_s)
return UnhandledPromptBehavior::DismissAndNotify;
if (unhandledPromptBehavior == "accept and notify"_s)
return UnhandledPromptBehavior::AcceptAndNotify;
if (unhandledPromptBehavior == "ignore"_s)
return UnhandledPromptBehavior::Ignore;
return std::nullopt;
}
void WebDriverService::parseCapabilities(const JSON::Object& matchedCapabilities, Capabilities& capabilities) const
{
// Matched capabilities have already been validated.
auto acceptInsecureCerts = matchedCapabilities.getBoolean("acceptInsecureCerts"_s);
if (acceptInsecureCerts)
capabilities.acceptInsecureCerts = *acceptInsecureCerts;
auto setWindowRect = matchedCapabilities.getBoolean("setWindowRect"_s);
if (setWindowRect)
capabilities.setWindowRect = *setWindowRect;
auto browserName = matchedCapabilities.getString("browserName"_s);
if (!!browserName)
capabilities.browserName = browserName;
auto browserVersion = matchedCapabilities.getString("browserVersion"_s);
if (!!browserVersion)
capabilities.browserVersion = browserVersion;
auto platformName = matchedCapabilities.getString("platformName"_s);
if (!!platformName)
capabilities.platformName = platformName;
auto proxy = matchedCapabilities.getObject("proxy"_s);
if (proxy)
capabilities.proxy = deserializeProxy(*proxy);
auto strictFileInteractability = matchedCapabilities.getBoolean("strictFileInteractability"_s);
if (strictFileInteractability)
capabilities.strictFileInteractability = *strictFileInteractability;
auto timeouts = matchedCapabilities.getObject("timeouts"_s);
if (timeouts)
capabilities.timeouts = deserializeTimeouts(*timeouts, IgnoreUnknownTimeout::No);
auto pageLoadStrategy = matchedCapabilities.getString("pageLoadStrategy"_s);
if (!!pageLoadStrategy)
capabilities.pageLoadStrategy = deserializePageLoadStrategy(pageLoadStrategy);
auto unhandledPromptBehavior = matchedCapabilities.getString("unhandledPromptBehavior"_s);
if (!!unhandledPromptBehavior)
capabilities.unhandledPromptBehavior = deserializeUnhandledPromptBehavior(unhandledPromptBehavior);
if (auto webSocketURL = matchedCapabilities.getBoolean("webSocketUrl"_s))
capabilities.webSocketURL = *webSocketURL;
platformParseCapabilities(matchedCapabilities, capabilities);
}
bool WebDriverService::findSessionOrCompleteWithError(JSON::Object& parameters, Function<void (CommandResult&&)>& completionHandler)
{
auto sessionID = parameters.getString("sessionId"_s);
if (!sessionID) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument));
return false;
}
if (!m_session || m_session->id() != sessionID) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidSessionID));
return false;
}
if (!m_session->isConnected()) {
m_session = nullptr;
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidSessionID, String("session deleted because of page crash or hang."_s)));
return false;
}
return true;
}
RefPtr<JSON::Object> WebDriverService::validatedCapabilities(const JSON::Object& capabilities) const
{
// §7.2 Processing Capabilities.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-validate-capabilities
auto result = JSON::Object::create();
auto end = capabilities.end();
for (auto it = capabilities.begin(); it != end; ++it) {
if (it->value->isNull())
continue;
if (it->key == "acceptInsecureCerts"_s) {
auto acceptInsecureCerts = it->value->asBoolean();
if (!acceptInsecureCerts)
return nullptr;
result->setBoolean(it->key, *acceptInsecureCerts);
} else if (it->key == "browserName"_s || it->key == "browserVersion"_s || it->key == "platformName"_s) {
auto stringValue = it->value->asString();
if (!stringValue)
return nullptr;
result->setString(it->key, stringValue);
} else if (it->key == "pageLoadStrategy"_s) {
auto pageLoadStrategy = it->value->asString();
if (!pageLoadStrategy || !deserializePageLoadStrategy(pageLoadStrategy))
return nullptr;
result->setString(it->key, pageLoadStrategy);
} else if (it->key == "proxy"_s) {
auto proxy = it->value->asObject();
if (!proxy || !deserializeProxy(*proxy))
return nullptr;
result->setValue(it->key, *proxy);
} else if (it->key == "strictFileInteractability"_s) {
auto strictFileInteractability = it->value->asBoolean();
if (!strictFileInteractability)
return nullptr;
result->setBoolean(it->key, *strictFileInteractability);
} else if (it->key == "timeouts"_s) {
auto timeouts = it->value->asObject();
if (!timeouts || !deserializeTimeouts(*timeouts, IgnoreUnknownTimeout::No))
return nullptr;
result->setValue(it->key, *timeouts);
} else if (it->key == "unhandledPromptBehavior"_s) {
auto unhandledPromptBehavior = it->value->asString();
if (!unhandledPromptBehavior || !deserializeUnhandledPromptBehavior(unhandledPromptBehavior))
return nullptr;
result->setString(it->key, unhandledPromptBehavior);
} else if (it->key.find(':') != notFound) {
if (!platformValidateCapability(it->key, it->value))
return nullptr;
result->setValue(it->key, it->value.copyRef());
} else if (it->key == "webSocketUrl"_s) {
auto webSocketURL = it->value->asBoolean();
if (!webSocketURL)
return nullptr;
result->setBoolean(it->key, *webSocketURL);
} else
return nullptr;
}
return result;
}
RefPtr<JSON::Object> WebDriverService::mergeCapabilities(const JSON::Object& requiredCapabilities, const JSON::Object& firstMatchCapabilities) const
{
// §7.2 Processing Capabilities.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-merging-capabilities
auto result = JSON::Object::create();
auto requiredEnd = requiredCapabilities.end();
for (auto it = requiredCapabilities.begin(); it != requiredEnd; ++it)
result->setValue(it->key, it->value.copyRef());
auto firstMatchEnd = firstMatchCapabilities.end();
for (auto it = firstMatchCapabilities.begin(); it != firstMatchEnd; ++it)
result->setValue(it->key, it->value.copyRef());
return result;
}
RefPtr<JSON::Object> WebDriverService::matchCapabilities(const JSON::Object& mergedCapabilities) const
{
// §7.2 Processing Capabilities.
// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-matching-capabilities
Capabilities platformCapabilities = this->platformCapabilities();
// Some capabilities like browser name and version might need to launch the browser,
// so we only reject the known capabilities that don't match.
auto matchedCapabilities = JSON::Object::create();
if (platformCapabilities.browserName)
matchedCapabilities->setString("browserName"_s, platformCapabilities.browserName.value());
if (platformCapabilities.browserVersion)
matchedCapabilities->setString("browserVersion"_s, platformCapabilities.browserVersion.value());
if (platformCapabilities.platformName)
matchedCapabilities->setString("platformName"_s, platformCapabilities.platformName.value());
if (platformCapabilities.acceptInsecureCerts)
matchedCapabilities->setBoolean("acceptInsecureCerts"_s, platformCapabilities.acceptInsecureCerts.value());
if (platformCapabilities.strictFileInteractability)
matchedCapabilities->setBoolean("strictFileInteractability"_s, platformCapabilities.strictFileInteractability.value());
if (platformCapabilities.setWindowRect)
matchedCapabilities->setBoolean("setWindowRect"_s, platformCapabilities.setWindowRect.value());
auto end = mergedCapabilities.end();
for (auto it = mergedCapabilities.begin(); it != end; ++it) {
if (it->key == "browserName"_s && platformCapabilities.browserName) {
auto browserName = it->value->asString();
if (!equalIgnoringASCIICase(platformCapabilities.browserName.value(), browserName))
return nullptr;
} else if (it->key == "browserVersion"_s && platformCapabilities.browserVersion) {
auto browserVersion = it->value->asString();
if (!platformCompareBrowserVersions(browserVersion, platformCapabilities.browserVersion.value()))
return nullptr;
} else if (it->key == "platformName"_s && platformCapabilities.platformName) {
auto platformName = it->value->asString();
if (!equalLettersIgnoringASCIICase(platformName, "any"_s) && platformCapabilities.platformName.value() != platformName)
return nullptr;
} else if (it->key == "acceptInsecureCerts"_s && platformCapabilities.acceptInsecureCerts) {
auto acceptInsecureCerts = it->value->asBoolean();
if (acceptInsecureCerts && !platformCapabilities.acceptInsecureCerts.value())
return nullptr;
} else if (it->key == "proxy"_s) {
auto proxyType = it->value->asObject()->getString("proxyType"_s);
if (!platformSupportProxyType(proxyType))
return nullptr;
} else if (it->key == "webSocketUrl"_s) {
auto webSocketURL = it->value->asBoolean();
if (webSocketURL && !platformSupportBidi())
return nullptr;
} else if (!platformMatchCapability(it->key, it->value))
return nullptr;
matchedCapabilities->setValue(it->key, it->value.copyRef());
}
return matchedCapabilities;
}
Vector<Capabilities> WebDriverService::processCapabilities(const JSON::Object& parameters, Function<void (CommandResult&&)>& completionHandler) const
{
// §7.2 Processing Capabilities.
// https://w3c.github.io/webdriver/webdriver-spec.html#processing-capabilities
// 1. Let capabilities request be the result of getting the property "capabilities" from parameters.
auto capabilitiesObject = parameters.getObject("capabilities"_s);
if (!capabilitiesObject) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument));
return { };
}
// 2. Let required capabilities be the result of getting the property "alwaysMatch" from capabilities request.
RefPtr<JSON::Object> requiredCapabilities;
auto requiredCapabilitiesValue = capabilitiesObject->getValue("alwaysMatch"_s);
if (!requiredCapabilitiesValue) {
// 2.1. If required capabilities is undefined, set the value to an empty JSON Object.
requiredCapabilities = JSON::Object::create();
} else if (!(requiredCapabilities = requiredCapabilitiesValue->asObject())) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument, String("alwaysMatch is invalid in capabilities"_s)));
return { };
}
// 2.2. Let required capabilities be the result of trying to validate capabilities with argument required capabilities.
requiredCapabilities = validatedCapabilities(*requiredCapabilities);
if (!requiredCapabilities) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument, String("Invalid alwaysMatch capabilities"_s)));
return { };
}
// 3. Let all first match capabilities be the result of getting the property "firstMatch" from capabilities request.
RefPtr<JSON::Array> firstMatchCapabilitiesList;
auto firstMatchCapabilitiesValue = capabilitiesObject->getValue("firstMatch"_s);
if (!firstMatchCapabilitiesValue) {
// 3.1. If all first match capabilities is undefined, set the value to a JSON List with a single entry of an empty JSON Object.
firstMatchCapabilitiesList = JSON::Array::create();
firstMatchCapabilitiesList->pushObject(JSON::Object::create());
} else {
firstMatchCapabilitiesList = firstMatchCapabilitiesValue->asArray();
if (!firstMatchCapabilitiesList) {
// 3.2. If all first match capabilities is not a JSON List, return error with error code invalid argument.
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument, String("firstMatch is invalid in capabilities"_s)));
return { };
}
}
// 4. Let validated first match capabilities be an empty JSON List.
Vector<RefPtr<JSON::Object>> validatedFirstMatchCapabilitiesList;
auto firstMatchCapabilitiesListLength = firstMatchCapabilitiesList->length();
validatedFirstMatchCapabilitiesList.reserveInitialCapacity(firstMatchCapabilitiesListLength);
// 5. For each first match capabilities corresponding to an indexed property in all first match capabilities.
for (unsigned i = 0; i < firstMatchCapabilitiesListLength; ++i) {
auto firstMatchCapabilities = firstMatchCapabilitiesList->get(i)->asObject();
if (!firstMatchCapabilities) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument, String("Invalid capabilities found in firstMatch"_s)));
return { };
}
// 5.1. Let validated capabilities be the result of trying to validate capabilities with argument first match capabilities.
firstMatchCapabilities = validatedCapabilities(*firstMatchCapabilities);
if (!firstMatchCapabilities) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument, String("Invalid firstMatch capabilities"_s)));
return { };
}
// Validate here that firstMatchCapabilities don't shadow alwaysMatchCapabilities.
auto requiredEnd = requiredCapabilities->end();
auto firstMatchEnd = firstMatchCapabilities->end();
for (auto it = firstMatchCapabilities->begin(); it != firstMatchEnd; ++it) {
if (requiredCapabilities->find(it->key) != requiredEnd) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::InvalidArgument,
makeString("Invalid firstMatch capabilities: key "_s, it->key, " is present in alwaysMatch"_s)));
return { };
}
}
// 5.2. Append validated capabilities to validated first match capabilities.
validatedFirstMatchCapabilitiesList.append(WTFMove(firstMatchCapabilities));
}
// 6. For each first match capabilities corresponding to an indexed property in validated first match capabilities.
Vector<Capabilities> matchedCapabilitiesList;
matchedCapabilitiesList.reserveInitialCapacity(validatedFirstMatchCapabilitiesList.size());
for (auto& validatedFirstMatchCapabilies : validatedFirstMatchCapabilitiesList) {
// 6.1. Let merged capabilities be the result of trying to merge capabilities with required capabilities and first match capabilities as arguments.
auto mergedCapabilities = mergeCapabilities(*requiredCapabilities, *validatedFirstMatchCapabilies);
// 6.2. Let matched capabilities be the result of trying to match capabilities with merged capabilities as an argument.
if (auto matchedCapabilities = matchCapabilities(*mergedCapabilities)) {
// 6.3. If matched capabilities is not null return matched capabilities.
Capabilities capabilities;
parseCapabilities(*matchedCapabilities, capabilities);
matchedCapabilitiesList.append(WTFMove(capabilities));
}
}
if (matchedCapabilitiesList.isEmpty()) {
completionHandler(CommandResult::fail(CommandResult::ErrorCode::SessionNotCreated, String("Failed to match capabilities"_s)));
return { };