forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_channel_test.cc
3188 lines (2825 loc) · 128 KB
/
websocket_channel_test.cc
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 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/websockets/websocket_channel.h"
#include <limits.h>
#include <stddef.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_piece.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/completion_once_callback.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "net/log/net_log_with_source.h"
#include "net/test/test_with_scoped_task_environment.h"
#include "net/url_request/url_request_context.h"
#include "net/websockets/websocket_errors.h"
#include "net/websockets/websocket_event_interface.h"
#include "net/websockets/websocket_handshake_request_info.h"
#include "net/websockets/websocket_handshake_response_info.h"
#include "net/websockets/websocket_handshake_stream_create_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
// Hacky macros to construct the body of a Close message from a code and a
// string, while ensuring the result is a compile-time constant string.
// Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
#define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
#define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
#define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
#define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
#define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
#define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
namespace net {
class WebSocketBasicHandshakeStream;
class WebSocketHttp2HandshakeStream;
// Printing helpers to allow GoogleMock to print frames. These are explicitly
// designed to look like the static initialisation format we use in these
// tests. They have to live in the net namespace in order to be found by
// GoogleMock; a nested anonymous namespace will not work.
std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
<< header.opcode << ", "
<< (header.masked ? "MASKED" : "NOT_MASKED");
}
std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
os << "{" << frame.header << ", ";
if (frame.data.get()) {
return os << "\"" << base::StringPiece(frame.data->data(),
frame.header.payload_length)
<< "\"}";
}
return os << "NULL}";
}
std::ostream& operator<<(
std::ostream& os,
const std::vector<std::unique_ptr<WebSocketFrame>>& frames) {
os << "{";
bool first = true;
for (const auto& frame : frames) {
if (!first) {
os << ",\n";
} else {
first = false;
}
os << *frame;
}
return os << "}";
}
std::ostream& operator<<(
std::ostream& os,
const std::vector<std::unique_ptr<WebSocketFrame>>* vector) {
return os << '&' << *vector;
}
namespace {
using ::base::TimeDelta;
using ::testing::AnyNumber;
using ::testing::DefaultValue;
using ::testing::InSequence;
using ::testing::MockFunction;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::StrictMock;
using ::testing::_;
// A selection of characters that have traditionally been mangled in some
// environment or other, for testing 8-bit cleanliness.
const char kBinaryBlob[] = {'\n', '\r', // BACKWARDS CRNL
'\0', // nul
'\x7F', // DEL
'\x80', '\xFF', // NOT VALID UTF-8
'\x1A', // Control-Z, EOF on DOS
'\x03', // Control-C
'\x04', // EOT, special for Unix terms
'\x1B', // ESC, often special
'\b', // backspace
'\'', // single-quote, special in PHP
};
const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
// The amount of quota a new connection gets by default.
// TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
// need to be updated.
const size_t kDefaultInitialQuota = 1 << 17;
// The amount of bytes we need to send after the initial connection to trigger a
// quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
// kDefaultSendQuotaLowWaterMark change.
const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
const int kVeryBigTimeoutMillis = 60 * 60 * 24 * 1000;
// TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
// in that time! I would like my tests to run a bit quicker.
const int kVeryTinyTimeoutMillis = 1;
// Enough quota to pass any test.
const int64_t kPlentyOfQuota = INT_MAX;
using ChannelState = WebSocketChannel::ChannelState;
constexpr ChannelState CHANNEL_ALIVE = WebSocketChannel::CHANNEL_ALIVE;
constexpr ChannelState CHANNEL_DELETED = WebSocketChannel::CHANNEL_DELETED;
// This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
// all over the place.
typedef StrictMock< MockFunction<void(int)> > Checkpoint; // NOLINT
// This mock is for testing expectations about how the EventInterface is used.
class MockWebSocketEventInterface : public WebSocketEventInterface {
public:
MockWebSocketEventInterface() = default;
void OnDataFrame(bool fin,
WebSocketMessageType type,
scoped_refptr<IOBuffer> buffer,
size_t buffer_size) override {
const char* data = buffer ? buffer->data() : nullptr;
return OnDataFrameVector(fin, type,
std::vector<char>(data, data + buffer_size));
}
MOCK_METHOD1(OnCreateURLRequest, void(URLRequest*));
MOCK_METHOD2(OnAddChannelResponse,
void(const std::string&,
const std::string&)); // NOLINT
MOCK_METHOD3(OnDataFrameVector,
void(bool,
WebSocketMessageType,
const std::vector<char>&)); // NOLINT
MOCK_METHOD1(OnFlowControl, void(int64_t)); // NOLINT
MOCK_METHOD0(OnClosingHandshake, void(void)); // NOLINT
MOCK_METHOD1(OnFailChannel, void(const std::string&)); // NOLINT
MOCK_METHOD3(OnDropChannel,
void(bool, uint16_t, const std::string&)); // NOLINT
// We can't use GMock with std::unique_ptr.
void OnStartOpeningHandshake(
std::unique_ptr<WebSocketHandshakeRequestInfo>) override {
OnStartOpeningHandshakeCalled();
}
void OnFinishOpeningHandshake(
std::unique_ptr<WebSocketHandshakeResponseInfo>) override {
OnFinishOpeningHandshakeCalled();
}
void OnSSLCertificateError(
std::unique_ptr<SSLErrorCallbacks> ssl_error_callbacks,
const GURL& url,
const SSLInfo& ssl_info,
bool fatal) override {
OnSSLCertificateErrorCalled(
ssl_error_callbacks.get(), url, ssl_info, fatal);
}
int OnAuthRequired(scoped_refptr<AuthChallengeInfo> auth_info,
scoped_refptr<HttpResponseHeaders> response_headers,
const HostPortPair& host_port_pair,
base::OnceCallback<void(const AuthCredentials*)> callback,
base::Optional<AuthCredentials>* credentials) override {
return OnAuthRequiredCalled(std::move(auth_info),
std::move(response_headers), host_port_pair,
credentials);
}
MOCK_METHOD0(OnStartOpeningHandshakeCalled, void()); // NOLINT
MOCK_METHOD0(OnFinishOpeningHandshakeCalled, void()); // NOLINT
MOCK_METHOD4(
OnSSLCertificateErrorCalled,
void(SSLErrorCallbacks*, const GURL&, const SSLInfo&, bool)); // NOLINT
MOCK_METHOD4(OnAuthRequiredCalled,
int(scoped_refptr<AuthChallengeInfo>,
scoped_refptr<HttpResponseHeaders>,
const HostPortPair&,
base::Optional<AuthCredentials>*));
};
// This fake EventInterface is for tests which need a WebSocketEventInterface
// implementation but are not verifying how it is used.
class FakeWebSocketEventInterface : public WebSocketEventInterface {
void OnCreateURLRequest(URLRequest* request) override {}
void OnAddChannelResponse(const std::string& selected_protocol,
const std::string& extensions) override {}
void OnDataFrame(bool fin,
WebSocketMessageType type,
scoped_refptr<IOBuffer> data,
size_t data_size) override {}
void OnFlowControl(int64_t quota) override {}
void OnClosingHandshake() override {}
void OnFailChannel(const std::string& message) override {}
void OnDropChannel(bool was_clean,
uint16_t code,
const std::string& reason) override {}
void OnStartOpeningHandshake(
std::unique_ptr<WebSocketHandshakeRequestInfo> request) override {}
void OnFinishOpeningHandshake(
std::unique_ptr<WebSocketHandshakeResponseInfo> response) override {}
void OnSSLCertificateError(
std::unique_ptr<SSLErrorCallbacks> ssl_error_callbacks,
const GURL& url,
const SSLInfo& ssl_info,
bool fatal) override {}
int OnAuthRequired(scoped_refptr<AuthChallengeInfo> auth_info,
scoped_refptr<HttpResponseHeaders> response_headers,
const HostPortPair& host_port_pair,
base::OnceCallback<void(const AuthCredentials*)> callback,
base::Optional<AuthCredentials>* credentials) override {
*credentials = base::nullopt;
return OK;
}
};
// This fake WebSocketStream is for tests that require a WebSocketStream but are
// not testing the way it is used. It has minimal functionality to return
// the |protocol| and |extensions| that it was constructed with.
class FakeWebSocketStream : public WebSocketStream {
public:
// Constructs with empty protocol and extensions.
FakeWebSocketStream() = default;
// Constructs with specified protocol and extensions.
FakeWebSocketStream(const std::string& protocol,
const std::string& extensions)
: protocol_(protocol), extensions_(extensions) {}
int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
return ERR_IO_PENDING;
}
int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
return ERR_IO_PENDING;
}
void Close() override {}
// Returns the string passed to the constructor.
std::string GetSubProtocol() const override { return protocol_; }
// Returns the string passed to the constructor.
std::string GetExtensions() const override { return extensions_; }
private:
// The string to return from GetSubProtocol().
std::string protocol_;
// The string to return from GetExtensions().
std::string extensions_;
};
// To make the static initialisers easier to read, we use enums rather than
// bools.
enum IsFinal { NOT_FINAL_FRAME, FINAL_FRAME };
enum IsMasked { NOT_MASKED, MASKED };
// This is used to initialise a WebSocketFrame but is statically initialisable.
struct InitFrame {
IsFinal final;
// Reserved fields omitted for now. Add them if you need them.
WebSocketFrameHeader::OpCode opcode;
IsMasked masked;
// Will be used to create the IOBuffer member. Can be null for null data. Is a
// nul-terminated string for ease-of-use. |header.payload_length| is
// initialised from |strlen(data)|. This means it is not 8-bit clean, but this
// is not an issue for test data.
const char* const data;
};
// For GoogleMock
std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
<< ", " << frame.opcode << ", "
<< (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
if (frame.data) {
return os << "\"" << frame.data << "\"}";
}
return os << "NULL}";
}
template <size_t N>
std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
os << "{";
bool first = true;
for (size_t i = 0; i < N; ++i) {
if (!first) {
os << ",\n";
} else {
first = false;
}
os << frames[i];
}
return os << "}";
}
// Convert a const array of InitFrame structs to the format used at
// runtime. Templated on the size of the array to save typing.
template <size_t N>
std::vector<std::unique_ptr<WebSocketFrame>> CreateFrameVector(
const InitFrame (&source_frames)[N]) {
std::vector<std::unique_ptr<WebSocketFrame>> result_frames;
result_frames.reserve(N);
for (size_t i = 0; i < N; ++i) {
const InitFrame& source_frame = source_frames[i];
auto result_frame = std::make_unique<WebSocketFrame>(source_frame.opcode);
size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
WebSocketFrameHeader& result_header = result_frame->header;
result_header.final = (source_frame.final == FINAL_FRAME);
result_header.masked = (source_frame.masked == MASKED);
result_header.payload_length = frame_length;
if (source_frame.data) {
result_frame->data = base::MakeRefCounted<IOBuffer>(frame_length);
memcpy(result_frame->data->data(), source_frame.data, frame_length);
}
result_frames.push_back(std::move(result_frame));
}
return result_frames;
}
// A GoogleMock action which can be used to respond to call to ReadFrames with
// some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
// |frames| is an array of InitFrame. |frames| needs to be passed by pointer
// because otherwise it will be treated as a pointer and the array size
// information will be lost.
ACTION_P(ReturnFrames, source_frames) {
*arg0 = CreateFrameVector(*source_frames);
return OK;
}
// The implementation of a GoogleMock matcher which can be used to compare a
// std::vector<std::unique_ptr<WebSocketFrame>>* against an expectation defined
// as an
// array of InitFrame objects. Although it is possible to compose built-in
// GoogleMock matchers to check the contents of a WebSocketFrame, the results
// are so unreadable that it is better to use this matcher.
template <size_t N>
class EqualsFramesMatcher : public ::testing::MatcherInterface<
std::vector<std::unique_ptr<WebSocketFrame>>*> {
public:
explicit EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
: expect_frames_(expect_frames) {}
virtual bool MatchAndExplain(
std::vector<std::unique_ptr<WebSocketFrame>>* actual_frames,
::testing::MatchResultListener* listener) const {
if (actual_frames->size() != N) {
*listener << "the vector size is " << actual_frames->size();
return false;
}
for (size_t i = 0; i < N; ++i) {
const WebSocketFrame& actual_frame = *(*actual_frames)[i];
const InitFrame& expected_frame = (*expect_frames_)[i];
if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
*listener << "the frame is marked as "
<< (actual_frame.header.final ? "" : "not ") << "final";
return false;
}
if (actual_frame.header.opcode != expected_frame.opcode) {
*listener << "the opcode is " << actual_frame.header.opcode;
return false;
}
if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
*listener << "the frame is "
<< (actual_frame.header.masked ? "masked" : "not masked");
return false;
}
const size_t expected_length =
expected_frame.data ? strlen(expected_frame.data) : 0;
if (actual_frame.header.payload_length != expected_length) {
*listener << "the payload length is "
<< actual_frame.header.payload_length;
return false;
}
if (expected_length != 0 &&
memcmp(actual_frame.data->data(),
expected_frame.data,
actual_frame.header.payload_length) != 0) {
*listener << "the data content differs";
return false;
}
}
return true;
}
virtual void DescribeTo(std::ostream* os) const {
*os << "matches " << *expect_frames_;
}
virtual void DescribeNegationTo(std::ostream* os) const {
*os << "does not match " << *expect_frames_;
}
private:
const InitFrame (*expect_frames_)[N];
};
// The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
// action, this can take the array by reference.
template <size_t N>
::testing::Matcher<std::vector<std::unique_ptr<WebSocketFrame>>*> EqualsFrames(
const InitFrame (&frames)[N]) {
return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
}
// A GoogleMock action to run a Closure.
ACTION_P(InvokeClosure, closure) { closure.Run(); }
// A FakeWebSocketStream whose ReadFrames() function returns data.
class ReadableFakeWebSocketStream : public FakeWebSocketStream {
public:
enum IsSync { SYNC, ASYNC };
// After constructing the object, call PrepareReadFrames() once for each
// time you wish it to return from the test.
ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
// Check that all the prepared responses have been consumed.
~ReadableFakeWebSocketStream() override {
CHECK(index_ >= responses_.size());
CHECK(!read_frames_pending_);
}
// Prepares a fake response. Fake responses will be returned from ReadFrames()
// in the same order they were prepared with PrepareReadFrames() and
// PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
// return ERR_IO_PENDING and the callback will be scheduled to run on the
// message loop. This requires the test case to run the message loop. If
// |async| is SYNC, the response will be returned synchronously. |error| is
// returned directly from ReadFrames() in the synchronous case, or passed to
// the callback in the asynchronous case. |frames| will be converted to a
// std::vector<std::unique_ptr<WebSocketFrame>> and copied to the pointer that
// was
// passed to ReadFrames().
template <size_t N>
void PrepareReadFrames(IsSync async,
int error,
const InitFrame (&frames)[N]) {
responses_.push_back(
std::make_unique<Response>(async, error, CreateFrameVector(frames)));
}
// An alternate version of PrepareReadFrames for when we need to construct
// the frames manually.
void PrepareRawReadFrames(
IsSync async,
int error,
std::vector<std::unique_ptr<WebSocketFrame>> frames) {
responses_.push_back(
std::make_unique<Response>(async, error, std::move(frames)));
}
// Prepares a fake error response (ie. there is no data).
void PrepareReadFramesError(IsSync async, int error) {
responses_.push_back(std::make_unique<Response>(
async, error, std::vector<std::unique_ptr<WebSocketFrame>>()));
}
int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
CHECK(!read_frames_pending_);
if (index_ >= responses_.size())
return ERR_IO_PENDING;
if (responses_[index_]->async == ASYNC) {
read_frames_pending_ = true;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&ReadableFakeWebSocketStream::DoCallback,
base::Unretained(this), frames, std::move(callback)));
return ERR_IO_PENDING;
} else {
frames->swap(responses_[index_]->frames);
return responses_[index_++]->error;
}
}
private:
void DoCallback(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) {
read_frames_pending_ = false;
frames->swap(responses_[index_]->frames);
std::move(callback).Run(responses_[index_++]->error);
return;
}
struct Response {
Response(IsSync async,
int error,
std::vector<std::unique_ptr<WebSocketFrame>> frames)
: async(async), error(error), frames(std::move(frames)) {}
IsSync async;
int error;
std::vector<std::unique_ptr<WebSocketFrame>> frames;
private:
// Bad things will happen if we attempt to copy or assign |frames|.
DISALLOW_COPY_AND_ASSIGN(Response);
};
std::vector<std::unique_ptr<Response>> responses_;
// The index into the responses_ array of the next response to be returned.
size_t index_;
// True when an async response from ReadFrames() is pending. This only applies
// to "real" async responses. Once all the prepared responses have been
// returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
// not set to true.
bool read_frames_pending_;
};
// A FakeWebSocketStream where writes always complete successfully and
// synchronously.
class WriteableFakeWebSocketStream : public FakeWebSocketStream {
public:
int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
return OK;
}
};
// A FakeWebSocketStream where writes always fail.
class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
public:
int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
return ERR_CONNECTION_RESET;
}
};
// A FakeWebSocketStream which echoes any frames written back. Clears the
// "masked" header bit, but makes no other checks for validity. Tests using this
// must run the MessageLoop to receive the callback(s). If a message with opcode
// Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
// callback. The test must do something to cause WriteFrames() to be called,
// otherwise the ReadFrames() callback will never be called.
class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
public:
EchoeyFakeWebSocketStream() : read_frames_(nullptr), done_(false) {}
int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
stored_frames_.insert(stored_frames_.end(),
std::make_move_iterator(frames->begin()),
std::make_move_iterator(frames->end()));
frames->clear();
// Users of WebSocketStream will not expect the ReadFrames() callback to be
// called from within WriteFrames(), so post it to the message loop instead.
PostCallback();
return OK;
}
int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
read_callback_ = std::move(callback);
read_frames_ = frames;
if (done_)
PostCallback();
return ERR_IO_PENDING;
}
private:
void PostCallback() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
base::Unretained(this)));
}
void DoCallback() {
if (done_) {
std::move(read_callback_).Run(ERR_CONNECTION_CLOSED);
} else if (!stored_frames_.empty()) {
done_ = MoveFrames(read_frames_);
read_frames_ = nullptr;
std::move(read_callback_).Run(OK);
}
}
// Copy the frames stored in stored_frames_ to |out|, while clearing the
// "masked" header bit. Returns true if a Close Frame was seen, false
// otherwise.
bool MoveFrames(std::vector<std::unique_ptr<WebSocketFrame>>* out) {
bool seen_close = false;
*out = std::move(stored_frames_);
for (const auto& frame : *out) {
WebSocketFrameHeader& header = frame->header;
header.masked = false;
if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
seen_close = true;
}
return seen_close;
}
std::vector<std::unique_ptr<WebSocketFrame>> stored_frames_;
CompletionOnceCallback read_callback_;
// Owned by the caller of ReadFrames().
std::vector<std::unique_ptr<WebSocketFrame>>* read_frames_;
// True if we should close the connection.
bool done_;
};
// A FakeWebSocketStream where writes trigger a connection reset.
// This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
// and triggers ReadFrames to return a reset as well. Tests using this need to
// run the message loop. There are two tricky parts here:
// 1. Calling the write callback may call Close(), after which the read callback
// should not be called.
// 2. Calling either callback may delete the stream altogether.
class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
public:
ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
weak_ptr_factory_.GetWeakPtr(), std::move(callback),
ERR_CONNECTION_RESET));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
weak_ptr_factory_.GetWeakPtr(), std::move(read_callback_),
ERR_CONNECTION_RESET));
return ERR_IO_PENDING;
}
int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) override {
read_callback_ = std::move(callback);
return ERR_IO_PENDING;
}
void Close() override { closed_ = true; }
private:
void CallCallbackUnlessClosed(CompletionOnceCallback callback, int value) {
if (!closed_)
std::move(callback).Run(value);
}
CompletionOnceCallback read_callback_;
bool closed_;
// An IO error can result in the socket being deleted, so we use weak pointers
// to ensure correct behaviour in that case.
base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
};
// This mock is for verifying that WebSocket protocol semantics are obeyed (to
// the extent that they are implemented in WebSocketCommon).
class MockWebSocketStream : public WebSocketStream {
public:
// GMock cannot save or forward move-only types like CompletionOnceCallback,
// therefore they have to be converted into a copyable type like
// CompletionRepeatingCallback.
int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) {
return ReadFramesInternal(
frames, callback ? base::AdaptCallbackForRepeating(std::move(callback))
: CompletionRepeatingCallback());
}
int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
CompletionOnceCallback callback) {
return WriteFramesInternal(
frames, callback ? base::AdaptCallbackForRepeating(std::move(callback))
: CompletionRepeatingCallback());
}
MOCK_METHOD2(ReadFramesInternal,
int(std::vector<std::unique_ptr<WebSocketFrame>>*,
const CompletionRepeatingCallback&));
MOCK_METHOD2(WriteFramesInternal,
int(std::vector<std::unique_ptr<WebSocketFrame>>*,
const CompletionRepeatingCallback&));
MOCK_METHOD0(Close, void());
MOCK_CONST_METHOD0(GetSubProtocol, std::string());
MOCK_CONST_METHOD0(GetExtensions, std::string());
MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
};
class MockWebSocketStreamRequest : public WebSocketStreamRequest {
public:
MOCK_METHOD1(OnBasicHandshakeStreamCreated,
void(WebSocketBasicHandshakeStream* handshake_stream));
MOCK_METHOD1(OnHttp2HandshakeStreamCreated,
void(WebSocketHttp2HandshakeStream* handshake_stream));
MOCK_METHOD1(OnFailure, void(const std::string& message));
};
struct WebSocketStreamCreationCallbackArgumentSaver {
std::unique_ptr<WebSocketStreamRequest> Create(
const GURL& socket_url,
std::unique_ptr<WebSocketHandshakeStreamCreateHelper> create_helper,
const url::Origin& origin,
const GURL& site_for_cookies,
const HttpRequestHeaders& additional_headers,
URLRequestContext* url_request_context,
const NetLogWithSource& net_log,
std::unique_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
this->socket_url = socket_url;
this->create_helper = std::move(create_helper);
this->origin = origin;
this->site_for_cookies = site_for_cookies;
this->url_request_context = url_request_context;
this->net_log = net_log;
this->connect_delegate = std::move(connect_delegate);
return std::make_unique<MockWebSocketStreamRequest>();
}
GURL socket_url;
std::unique_ptr<WebSocketHandshakeStreamCreateHelper> create_helper;
url::Origin origin;
GURL site_for_cookies;
URLRequestContext* url_request_context;
NetLogWithSource net_log;
std::unique_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
};
std::vector<char> AsVector(const base::StringPiece& s) {
return std::vector<char>(s.begin(), s.end());
}
// Converts a base::StringPiece to a IOBuffer. For test purposes, it is
// convenient to be able to specify data as a string, but the
// WebSocketEventInterface requires the IOBuffer type.
scoped_refptr<IOBuffer> AsIOBuffer(const base::StringPiece& s) {
auto buffer = base::MakeRefCounted<IOBuffer>(s.size());
std::copy(s.begin(), s.end(), buffer->data());
return buffer;
}
class FakeSSLErrorCallbacks
: public WebSocketEventInterface::SSLErrorCallbacks {
public:
void CancelSSLRequest(int error, const SSLInfo* ssl_info) override {}
void ContinueSSLRequest() override {}
};
// Base class for all test fixtures.
class WebSocketChannelTest : public TestWithScopedTaskEnvironment {
protected:
WebSocketChannelTest() : stream_(std::make_unique<FakeWebSocketStream>()) {}
// Creates a new WebSocketChannel and connects it, using the settings stored
// in |connect_data_|.
void CreateChannelAndConnect() {
channel_ = std::make_unique<WebSocketChannel>(
CreateEventInterface(), &connect_data_.url_request_context);
channel_->SendAddChannelRequestForTesting(
connect_data_.socket_url, connect_data_.requested_subprotocols,
connect_data_.origin, connect_data_.site_for_cookies,
HttpRequestHeaders(),
base::Bind(&WebSocketStreamCreationCallbackArgumentSaver::Create,
base::Unretained(&connect_data_.argument_saver)));
}
// Same as CreateChannelAndConnect(), but calls the on_success callback as
// well. This method is virtual so that subclasses can also set the stream.
virtual void CreateChannelAndConnectSuccessfully() {
CreateChannelAndConnect();
// Most tests aren't concerned with flow control from the renderer, so allow
// MAX_INT quota units.
EXPECT_EQ(CHANNEL_ALIVE, channel_->SendFlowControl(kPlentyOfQuota));
connect_data_.argument_saver.connect_delegate->OnSuccess(
std::move(stream_));
}
// Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
// This implementation returns a newly-created fake. Subclasses may return a
// mock instead.
virtual std::unique_ptr<WebSocketEventInterface> CreateEventInterface() {
return std::make_unique<FakeWebSocketEventInterface>();
}
// This method serves no other purpose than to provide a nice syntax for
// assigning to stream_. class T must be a subclass of WebSocketStream or you
// will have unpleasant compile errors.
template <class T>
void set_stream(std::unique_ptr<T> stream) {
stream_ = std::move(stream);
}
// A struct containing the data that will be used to connect the channel.
// Grouped for readability.
struct ConnectData {
ConnectData()
: socket_url("ws://ws/"),
origin(url::Origin::Create(GURL("http://ws"))),
site_for_cookies("http://ws/") {}
// URLRequestContext object.
URLRequestContext url_request_context;
// URL to (pretend to) connect to.
GURL socket_url;
// Requested protocols for the request.
std::vector<std::string> requested_subprotocols;
// Origin of the request
url::Origin origin;
// First party for cookies for the request.
GURL site_for_cookies;
WebSocketStreamCreationCallbackArgumentSaver argument_saver;
};
ConnectData connect_data_;
// The channel we are testing. Not initialised until SetChannel() is called.
std::unique_ptr<WebSocketChannel> channel_;
// A mock or fake stream for tests that need one.
std::unique_ptr<WebSocketStream> stream_;
};
// enum of WebSocketEventInterface calls. These are intended to be or'd together
// in order to instruct WebSocketChannelDeletingTest when it should fail.
enum EventInterfaceCall {
EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
EVENT_ON_DATA_FRAME = 0x2,
EVENT_ON_FLOW_CONTROL = 0x4,
EVENT_ON_CLOSING_HANDSHAKE = 0x8,
EVENT_ON_FAIL_CHANNEL = 0x10,
EVENT_ON_DROP_CHANNEL = 0x20,
EVENT_ON_START_OPENING_HANDSHAKE = 0x40,
EVENT_ON_FINISH_OPENING_HANDSHAKE = 0x80,
EVENT_ON_SSL_CERTIFICATE_ERROR = 0x100,
};
// Base class for tests which verify that EventInterface methods are called
// appropriately.
class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
protected:
WebSocketChannelEventInterfaceTest()
: event_interface_(
std::make_unique<StrictMock<MockWebSocketEventInterface>>()) {
}
~WebSocketChannelEventInterfaceTest() override {
}
// Tests using this fixture must set expectations on the event_interface_ mock
// object before calling CreateChannelAndConnect() or
// CreateChannelAndConnectSuccessfully(). This will only work once per test
// case, but once should be enough.
std::unique_ptr<WebSocketEventInterface> CreateEventInterface() override {
return std::move(event_interface_);
}
std::unique_ptr<MockWebSocketEventInterface> event_interface_;
};
// Base class for tests which verify that WebSocketStream methods are called
// appropriately by using a MockWebSocketStream.
class WebSocketChannelStreamTest : public WebSocketChannelTest {
protected:
WebSocketChannelStreamTest()
: mock_stream_(std::make_unique<StrictMock<MockWebSocketStream>>()) {}
void CreateChannelAndConnectSuccessfully() override {
set_stream(std::move(mock_stream_));
WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
}
std::unique_ptr<MockWebSocketStream> mock_stream_;
};
// Fixture for tests which test UTF-8 validation of sent Text frames via the
// EventInterface.
class WebSocketChannelSendUtf8Test
: public WebSocketChannelEventInterfaceTest {
public:
void SetUp() override {
set_stream(std::make_unique<WriteableFakeWebSocketStream>());
// For the purpose of the tests using this fixture, it doesn't matter
// whether these methods are called or not.
EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _))
.Times(AnyNumber());
EXPECT_CALL(*event_interface_, OnFlowControl(_))
.Times(AnyNumber());
}
};
// Fixture for tests which test use of receive quota from the renderer.
class WebSocketChannelFlowControlTest
: public WebSocketChannelEventInterfaceTest {
protected:
// Tests using this fixture should use CreateChannelAndConnectWithQuota()
// instead of CreateChannelAndConnectSuccessfully().
void CreateChannelAndConnectWithQuota(int64_t quota) {
CreateChannelAndConnect();
EXPECT_EQ(CHANNEL_ALIVE, channel_->SendFlowControl(quota));
connect_data_.argument_saver.connect_delegate->OnSuccess(
std::move(stream_));
}
virtual void CreateChannelAndConnectSuccesfully() { NOTREACHED(); }
};
// Fixture for tests which test UTF-8 validation of received Text frames using a
// mock WebSocketStream.
class WebSocketChannelReceiveUtf8Test : public WebSocketChannelStreamTest {
public:
void SetUp() override {
// For the purpose of the tests using this fixture, it doesn't matter
// whether these methods are called or not.
EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
}
};
// Simple test that everything that should be passed to the stream creation
// callback is passed to the argument saver.
TEST_F(WebSocketChannelTest, EverythingIsPassedToTheCreatorFunction) {
connect_data_.socket_url = GURL("ws://example.com/test");
connect_data_.origin = url::Origin::Create(GURL("http://example.com"));
connect_data_.site_for_cookies = GURL("http://example.com/");
connect_data_.requested_subprotocols.push_back("Sinbad");
CreateChannelAndConnect();
const WebSocketStreamCreationCallbackArgumentSaver& actual =
connect_data_.argument_saver;
EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
EXPECT_EQ(connect_data_.origin.Serialize(), actual.origin.Serialize());
EXPECT_EQ(connect_data_.site_for_cookies, actual.site_for_cookies);
}
// Verify that calling SendFlowControl before the connection is established does
// not cause a crash.
TEST_F(WebSocketChannelTest, SendFlowControlDuringHandshakeOkay) {
CreateChannelAndConnect();
ASSERT_TRUE(channel_);
ASSERT_EQ(CHANNEL_ALIVE, channel_->SendFlowControl(65536));
}
TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
// false means success.
EXPECT_CALL(*event_interface_, OnAddChannelResponse("", ""));
// OnFlowControl is always called immediately after connect to provide initial
// quota to the renderer.
EXPECT_CALL(*event_interface_, OnFlowControl(_));
CreateChannelAndConnect();
connect_data_.argument_saver.connect_delegate->OnSuccess(std::move(stream_));