forked from Pissandshittium/pissandshittium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspdy_session.cc
3817 lines (3297 loc) · 136 KB
/
spdy_session.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 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/spdy/spdy_session.h"
#include <limits>
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "base/strings/abseil_string_conversions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "net/base/features.h"
#include "net/base/proxy_server.h"
#include "net/base/proxy_string_util.h"
#include "net/base/url_util.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/ct_policy_status.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties.h"
#include "net/http/http_util.h"
#include "net/http/http_vary_data.h"
#include "net/http/transport_security_state.h"
#include "net/log/net_log.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source_type.h"
#include "net/log/net_log_with_source.h"
#include "net/nqe/network_quality_estimator.h"
#include "net/quic/quic_http_utils.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket.h"
#include "net/socket/ssl_client_socket.h"
#include "net/spdy/alps_decoder.h"
#include "net/spdy/header_coalescer.h"
#include "net/spdy/spdy_buffer_producer.h"
#include "net/spdy/spdy_http_utils.h"
#include "net/spdy/spdy_log_util.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/spdy/spdy_stream.h"
#include "net/ssl/ssl_cipher_suite_names.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/third_party/quiche/src/quiche/quic/core/http/spdy_server_push_utils.h"
#include "net/third_party/quiche/src/quiche/spdy/core/spdy_frame_builder.h"
#include "net/third_party/quiche/src/quiche/spdy/core/spdy_protocol.h"
#include "url/scheme_host_port.h"
#include "url/url_constants.h"
namespace net {
namespace {
constexpr net::NetworkTrafficAnnotationTag
kSpdySessionCommandsTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("spdy_session_control", R"(
semantics {
sender: "Spdy Session"
description:
"Sends commands to control an HTTP/2 session."
trigger:
"Required control commands like initiating stream, requesting "
"stream reset, changing priorities, etc."
data: "No user data."
destination: OTHER
destination_other:
"Any destination the HTTP/2 session is connected to."
}
policy {
cookies_allowed: NO
setting: "This feature cannot be disabled in settings."
policy_exception_justification: "Essential for network access."
}
)");
const int kReadBufferSize = 8 * 1024;
const int kDefaultConnectionAtRiskOfLossSeconds = 10;
const int kHungIntervalSeconds = 10;
// Lifetime of unclaimed pushed stream, in seconds: after this period, a pushed
// stream is cancelled if still not claimed.
const int kPushedStreamLifetimeSeconds = 300;
// Default initial value for HTTP/2 SETTINGS.
const uint32_t kDefaultInitialHeaderTableSize = 4096;
const uint32_t kDefaultInitialEnablePush = 1;
const uint32_t kDefaultInitialInitialWindowSize = 65535;
const uint32_t kDefaultInitialMaxFrameSize = 16384;
// Values of Vary response header on pushed streams. This is logged to
// Net.PushedStreamVaryResponseHeader, entries must not be changed.
enum PushedStreamVaryResponseHeaderValues {
// There is no Vary header.
kNoVaryHeader = 0,
// The value of Vary is empty.
kVaryIsEmpty = 1,
// The value of Vary is "*".
kVaryIsStar = 2,
// The value of Vary is "accept-encoding" (case insensitive).
kVaryIsAcceptEncoding = 3,
// The value of Vary contains "accept-encoding" (case insensitive) and some
// other field names as well.
kVaryHasAcceptEncoding = 4,
// The value of Vary does not contain "accept-encoding", is not empty, and is
// not "*".
kVaryHasNoAcceptEncoding = 5,
// The number of entries above.
kNumberOfVaryEntries = 6
};
// These values are persisted to logs. Entries should not be renumbered, and
// numeric values should never be reused.
enum class SpdyAcceptChEntries {
kNoEntries = 0,
kOnlyValidEntries = 1,
kOnlyInvalidEntries = 2,
kBothValidAndInvalidEntries = 3,
kMaxValue = kBothValidAndInvalidEntries,
};
// String literals for parsing the Vary header in a pushed response.
const char kVary[] = "vary";
const char kStar[] = "*";
const char kAcceptEncoding[] = "accept-encoding";
enum PushedStreamVaryResponseHeaderValues ParseVaryInPushedResponse(
const spdy::Http2HeaderBlock& headers) {
spdy::Http2HeaderBlock::iterator it = headers.find(kVary);
if (it == headers.end())
return kNoVaryHeader;
base::StringPiece value = base::StringViewToStringPiece(it->second);
if (value.empty())
return kVaryIsEmpty;
if (value == kStar)
return kVaryIsStar;
std::string lowercase_value = base::ToLowerASCII(value);
if (lowercase_value == kAcceptEncoding)
return kVaryIsAcceptEncoding;
// Both comma and newline delimiters occur in the wild.
for (const auto& substr :
SplitString(lowercase_value, ",\n", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY)) {
if (substr == kAcceptEncoding)
return kVaryHasAcceptEncoding;
}
return kVaryHasNoAcceptEncoding;
}
// A SpdyBufferProducer implementation that creates an HTTP/2 frame by adding
// stream ID to greased frame parameters.
class GreasedBufferProducer : public SpdyBufferProducer {
public:
GreasedBufferProducer() = delete;
GreasedBufferProducer(
base::WeakPtr<SpdyStream> stream,
const SpdySessionPool::GreasedHttp2Frame* greased_http2_frame,
BufferedSpdyFramer* buffered_spdy_framer)
: stream_(stream),
greased_http2_frame_(greased_http2_frame),
buffered_spdy_framer_(buffered_spdy_framer) {}
~GreasedBufferProducer() override = default;
std::unique_ptr<SpdyBuffer> ProduceBuffer() override {
const spdy::SpdyStreamId stream_id = stream_ ? stream_->stream_id() : 0;
spdy::SpdyUnknownIR frame(stream_id, greased_http2_frame_->type,
greased_http2_frame_->flags,
greased_http2_frame_->payload);
auto serialized_frame = std::make_unique<spdy::SpdySerializedFrame>(
buffered_spdy_framer_->SerializeFrame(frame));
return std::make_unique<SpdyBuffer>(std::move(serialized_frame));
}
private:
base::WeakPtr<SpdyStream> stream_;
const raw_ptr<const SpdySessionPool::GreasedHttp2Frame> greased_http2_frame_;
raw_ptr<BufferedSpdyFramer> buffered_spdy_framer_;
};
bool IsSpdySettingAtDefaultInitialValue(spdy::SpdySettingsId setting_id,
uint32_t value) {
switch (setting_id) {
case spdy::SETTINGS_HEADER_TABLE_SIZE:
return value == kDefaultInitialHeaderTableSize;
case spdy::SETTINGS_ENABLE_PUSH:
return value == kDefaultInitialEnablePush;
case spdy::SETTINGS_MAX_CONCURRENT_STREAMS:
// There is no initial limit on the number of concurrent streams.
return false;
case spdy::SETTINGS_INITIAL_WINDOW_SIZE:
return value == kDefaultInitialInitialWindowSize;
case spdy::SETTINGS_MAX_FRAME_SIZE:
return value == kDefaultInitialMaxFrameSize;
case spdy::SETTINGS_MAX_HEADER_LIST_SIZE:
// There is no initial limit on the size of the header list.
return false;
case spdy::SETTINGS_ENABLE_CONNECT_PROTOCOL:
return value == 0;
default:
// Undefined parameters have no initial value.
return false;
}
}
bool IsPushEnabled(const spdy::SettingsMap& initial_settings) {
const auto it = initial_settings.find(spdy::SETTINGS_ENABLE_PUSH);
// Push is enabled by default.
if (it == initial_settings.end())
return true;
return it->second == 1;
}
void LogSpdyAcceptChForOriginHistogram(bool value) {
base::UmaHistogramBoolean("Net.SpdySession.AcceptChForOrigin", value);
}
base::Value NetLogSpdyHeadersSentParams(const spdy::Http2HeaderBlock* headers,
bool fin,
spdy::SpdyStreamId stream_id,
bool has_priority,
int weight,
spdy::SpdyStreamId parent_stream_id,
bool exclusive,
NetLogSource source_dependency,
NetLogCaptureMode capture_mode) {
base::Value::Dict dict;
dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode));
dict.Set("fin", fin);
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("has_priority", has_priority);
if (has_priority) {
dict.Set("parent_stream_id", static_cast<int>(parent_stream_id));
dict.Set("weight", weight);
dict.Set("exclusive", exclusive);
}
if (source_dependency.IsValid()) {
source_dependency.AddToEventParameters(dict);
}
return base::Value(std::move(dict));
}
base::Value NetLogSpdyHeadersReceivedParams(
const spdy::Http2HeaderBlock* headers,
bool fin,
spdy::SpdyStreamId stream_id,
NetLogCaptureMode capture_mode) {
base::Value::Dict dict;
dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode));
dict.Set("fin", fin);
dict.Set("stream_id", static_cast<int>(stream_id));
return base::Value(std::move(dict));
}
base::Value NetLogSpdySessionCloseParams(int net_error,
const std::string& description) {
base::Value::Dict dict;
dict.Set("net_error", net_error);
dict.Set("description", description);
return base::Value(std::move(dict));
}
base::Value NetLogSpdySessionParams(const HostPortProxyPair& host_pair) {
base::Value::Dict dict;
dict.Set("host", host_pair.first.ToString());
dict.Set("proxy", ProxyServerToPacResultElement(host_pair.second));
return base::Value(std::move(dict));
}
base::Value NetLogSpdyInitializedParams(NetLogSource source) {
base::Value::Dict dict;
if (source.IsValid()) {
source.AddToEventParameters(dict);
}
dict.Set("protocol", NextProtoToString(kProtoHTTP2));
return base::Value(std::move(dict));
}
base::Value NetLogSpdySendSettingsParams(const spdy::SettingsMap* settings) {
base::Value::Dict dict;
base::Value::List settings_list;
for (const auto& setting : *settings) {
const spdy::SpdySettingsId id = setting.first;
const uint32_t value = setting.second;
settings_list.Append(
base::StringPrintf("[id:%u (%s) value:%u]", id,
spdy::SettingsIdToString(id).c_str(), value));
}
dict.Set("settings", std::move(settings_list));
return base::Value(std::move(dict));
}
base::Value NetLogSpdyRecvAcceptChParams(spdy::AcceptChOriginValuePair entry) {
base::Value::Dict dict;
dict.Set("origin", entry.origin);
dict.Set("accept_ch", entry.value);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyRecvSettingParams(spdy::SpdySettingsId id,
uint32_t value) {
base::Value::Dict dict;
dict.Set("id", base::StringPrintf("%u (%s)", id,
spdy::SettingsIdToString(id).c_str()));
dict.Set("value", static_cast<int>(value));
return base::Value(std::move(dict));
}
base::Value NetLogSpdyWindowUpdateFrameParams(spdy::SpdyStreamId stream_id,
uint32_t delta) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("delta", static_cast<int>(delta));
return base::Value(std::move(dict));
}
base::Value NetLogSpdySessionWindowUpdateParams(int32_t delta,
int32_t window_size) {
base::Value::Dict dict;
dict.Set("delta", delta);
dict.Set("window_size", window_size);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyDataParams(spdy::SpdyStreamId stream_id,
int size,
bool fin) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("size", size);
dict.Set("fin", fin);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyRecvRstStreamParams(spdy::SpdyStreamId stream_id,
spdy::SpdyErrorCode error_code) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("error_code", base::StringPrintf("%u (%s)", error_code,
ErrorCodeToString(error_code)));
return base::Value(std::move(dict));
}
base::Value NetLogSpdySendRstStreamParams(spdy::SpdyStreamId stream_id,
spdy::SpdyErrorCode error_code,
const std::string& description) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("error_code", base::StringPrintf("%u (%s)", error_code,
ErrorCodeToString(error_code)));
dict.Set("description", description);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyPingParams(spdy::SpdyPingId unique_id,
bool is_ack,
const char* type) {
base::Value::Dict dict;
dict.Set("unique_id", static_cast<int>(unique_id));
dict.Set("type", type);
dict.Set("is_ack", is_ack);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyRecvGoAwayParams(spdy::SpdyStreamId last_stream_id,
int active_streams,
int unclaimed_streams,
spdy::SpdyErrorCode error_code,
base::StringPiece debug_data,
NetLogCaptureMode capture_mode) {
base::Value::Dict dict;
dict.Set("last_accepted_stream_id", static_cast<int>(last_stream_id));
dict.Set("active_streams", active_streams);
dict.Set("unclaimed_streams", unclaimed_streams);
dict.Set("error_code", base::StringPrintf("%u (%s)", error_code,
ErrorCodeToString(error_code)));
dict.Set("debug_data",
ElideGoAwayDebugDataForNetLog(capture_mode, debug_data));
return base::Value(std::move(dict));
}
base::Value NetLogSpdyPushPromiseReceivedParams(
const spdy::Http2HeaderBlock* headers,
spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId promised_stream_id,
NetLogCaptureMode capture_mode) {
base::Value::Dict dict;
dict.Set("headers", ElideHttp2HeaderBlockForNetLog(*headers, capture_mode));
dict.Set("id", static_cast<int>(stream_id));
dict.Set("promised_stream_id", static_cast<int>(promised_stream_id));
return base::Value(std::move(dict));
}
base::Value NetLogSpdyAdoptedPushStreamParams(spdy::SpdyStreamId stream_id,
const GURL& url) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("url", url.spec());
return base::Value(std::move(dict));
}
base::Value NetLogSpdySessionStalledParams(size_t num_active_streams,
size_t num_created_streams,
size_t num_pushed_streams,
size_t max_concurrent_streams,
const std::string& url) {
base::Value::Dict dict;
dict.Set("num_active_streams", static_cast<int>(num_active_streams));
dict.Set("num_created_streams", static_cast<int>(num_created_streams));
dict.Set("num_pushed_streams", static_cast<int>(num_pushed_streams));
dict.Set("max_concurrent_streams", static_cast<int>(max_concurrent_streams));
dict.Set("url", url);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyPriorityParams(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId parent_stream_id,
int weight,
bool exclusive) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("parent_stream_id", static_cast<int>(parent_stream_id));
dict.Set("weight", weight);
dict.Set("exclusive", exclusive);
return base::Value(std::move(dict));
}
base::Value NetLogSpdyGreasedFrameParams(spdy::SpdyStreamId stream_id,
uint8_t type,
uint8_t flags,
size_t length,
RequestPriority priority) {
base::Value::Dict dict;
dict.Set("stream_id", static_cast<int>(stream_id));
dict.Set("type", type);
dict.Set("flags", flags);
dict.Set("length", static_cast<int>(length));
dict.Set("priority", RequestPriorityToString(priority));
return base::Value(std::move(dict));
}
// Helper function to return the total size of an array of objects
// with .size() member functions.
template <typename T, size_t N>
size_t GetTotalSize(const T (&arr)[N]) {
size_t total_size = 0;
for (size_t i = 0; i < N; ++i) {
total_size += arr[i].size();
}
return total_size;
}
// The maximum number of concurrent streams we will ever create. Even if
// the server permits more, we will never exceed this limit.
const size_t kMaxConcurrentStreamLimit = 256;
class SpdyServerPushHelper : public ServerPushDelegate::ServerPushHelper {
public:
explicit SpdyServerPushHelper(base::WeakPtr<SpdySession> session,
const GURL& url)
: session_(session), request_url_(url) {}
void Cancel() override {
if (session_)
session_->CancelPush(request_url_);
}
const GURL& GetURL() const override { return request_url_; }
NetworkAnonymizationKey GetNetworkAnonymizationKey() const override {
if (session_) {
return session_->spdy_session_key().network_anonymization_key();
}
return NetworkAnonymizationKey();
}
private:
base::WeakPtr<SpdySession> session_;
const GURL request_url_;
};
} // namespace
SpdyProtocolErrorDetails MapFramerErrorToProtocolError(
http2::Http2DecoderAdapter::SpdyFramerError err) {
switch (err) {
case http2::Http2DecoderAdapter::SPDY_NO_ERROR:
return SPDY_ERROR_NO_ERROR;
case http2::Http2DecoderAdapter::SPDY_INVALID_STREAM_ID:
return SPDY_ERROR_INVALID_STREAM_ID;
case http2::Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME:
return SPDY_ERROR_INVALID_CONTROL_FRAME;
case http2::Http2DecoderAdapter::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
return SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE;
case http2::Http2DecoderAdapter::SPDY_DECOMPRESS_FAILURE:
return SPDY_ERROR_DECOMPRESS_FAILURE;
case http2::Http2DecoderAdapter::SPDY_INVALID_PADDING:
return SPDY_ERROR_INVALID_PADDING;
case http2::Http2DecoderAdapter::SPDY_INVALID_DATA_FRAME_FLAGS:
return SPDY_ERROR_INVALID_DATA_FRAME_FLAGS;
case http2::Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME:
return SPDY_ERROR_UNEXPECTED_FRAME;
case http2::Http2DecoderAdapter::SPDY_INTERNAL_FRAMER_ERROR:
return SPDY_ERROR_INTERNAL_FRAMER_ERROR;
case http2::Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE:
return SPDY_ERROR_INVALID_CONTROL_FRAME_SIZE;
case http2::Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD:
return SPDY_ERROR_OVERSIZED_PAYLOAD;
case http2::Http2DecoderAdapter::SPDY_HPACK_INDEX_VARINT_ERROR:
return SPDY_ERROR_HPACK_INDEX_VARINT_ERROR;
case http2::Http2DecoderAdapter::SPDY_HPACK_NAME_LENGTH_VARINT_ERROR:
return SPDY_ERROR_HPACK_NAME_LENGTH_VARINT_ERROR;
case http2::Http2DecoderAdapter::SPDY_HPACK_VALUE_LENGTH_VARINT_ERROR:
return SPDY_ERROR_HPACK_VALUE_LENGTH_VARINT_ERROR;
case http2::Http2DecoderAdapter::SPDY_HPACK_NAME_TOO_LONG:
return SPDY_ERROR_HPACK_NAME_TOO_LONG;
case http2::Http2DecoderAdapter::SPDY_HPACK_VALUE_TOO_LONG:
return SPDY_ERROR_HPACK_VALUE_TOO_LONG;
case http2::Http2DecoderAdapter::SPDY_HPACK_NAME_HUFFMAN_ERROR:
return SPDY_ERROR_HPACK_NAME_HUFFMAN_ERROR;
case http2::Http2DecoderAdapter::SPDY_HPACK_VALUE_HUFFMAN_ERROR:
return SPDY_ERROR_HPACK_VALUE_HUFFMAN_ERROR;
case http2::Http2DecoderAdapter::
SPDY_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE:
return SPDY_ERROR_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE;
case http2::Http2DecoderAdapter::SPDY_HPACK_INVALID_INDEX:
return SPDY_ERROR_HPACK_INVALID_INDEX;
case http2::Http2DecoderAdapter::SPDY_HPACK_INVALID_NAME_INDEX:
return SPDY_ERROR_HPACK_INVALID_NAME_INDEX;
case http2::Http2DecoderAdapter::
SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED:
return SPDY_ERROR_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED;
case http2::Http2DecoderAdapter::
SPDY_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK:
return SPDY_ERROR_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK;
case http2::Http2DecoderAdapter::
SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING:
return SPDY_ERROR_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING;
case http2::Http2DecoderAdapter::SPDY_HPACK_TRUNCATED_BLOCK:
return SPDY_ERROR_HPACK_TRUNCATED_BLOCK;
case http2::Http2DecoderAdapter::SPDY_HPACK_FRAGMENT_TOO_LONG:
return SPDY_ERROR_HPACK_FRAGMENT_TOO_LONG;
case http2::Http2DecoderAdapter::
SPDY_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT:
return SPDY_ERROR_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT;
case http2::Http2DecoderAdapter::SPDY_STOP_PROCESSING:
return SPDY_ERROR_STOP_PROCESSING;
case http2::Http2DecoderAdapter::LAST_ERROR:
NOTREACHED();
}
NOTREACHED();
return static_cast<SpdyProtocolErrorDetails>(-1);
}
Error MapFramerErrorToNetError(
http2::Http2DecoderAdapter::SpdyFramerError err) {
switch (err) {
case http2::Http2DecoderAdapter::SPDY_NO_ERROR:
return OK;
case http2::Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME:
return ERR_HTTP2_PROTOCOL_ERROR;
case http2::Http2DecoderAdapter::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
return ERR_HTTP2_FRAME_SIZE_ERROR;
case http2::Http2DecoderAdapter::SPDY_DECOMPRESS_FAILURE:
case http2::Http2DecoderAdapter::SPDY_HPACK_INDEX_VARINT_ERROR:
case http2::Http2DecoderAdapter::SPDY_HPACK_NAME_LENGTH_VARINT_ERROR:
case http2::Http2DecoderAdapter::SPDY_HPACK_VALUE_LENGTH_VARINT_ERROR:
case http2::Http2DecoderAdapter::SPDY_HPACK_NAME_TOO_LONG:
case http2::Http2DecoderAdapter::SPDY_HPACK_VALUE_TOO_LONG:
case http2::Http2DecoderAdapter::SPDY_HPACK_NAME_HUFFMAN_ERROR:
case http2::Http2DecoderAdapter::SPDY_HPACK_VALUE_HUFFMAN_ERROR:
case http2::Http2DecoderAdapter::
SPDY_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE:
case http2::Http2DecoderAdapter::SPDY_HPACK_INVALID_INDEX:
case http2::Http2DecoderAdapter::SPDY_HPACK_INVALID_NAME_INDEX:
case http2::Http2DecoderAdapter::
SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED:
case http2::Http2DecoderAdapter::
SPDY_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK:
case http2::Http2DecoderAdapter::
SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING:
case http2::Http2DecoderAdapter::SPDY_HPACK_TRUNCATED_BLOCK:
case http2::Http2DecoderAdapter::SPDY_HPACK_FRAGMENT_TOO_LONG:
case http2::Http2DecoderAdapter::
SPDY_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT:
return ERR_HTTP2_COMPRESSION_ERROR;
case http2::Http2DecoderAdapter::SPDY_STOP_PROCESSING:
return ERR_HTTP2_COMPRESSION_ERROR;
case http2::Http2DecoderAdapter::SPDY_INVALID_PADDING:
return ERR_HTTP2_PROTOCOL_ERROR;
case http2::Http2DecoderAdapter::SPDY_INVALID_DATA_FRAME_FLAGS:
return ERR_HTTP2_PROTOCOL_ERROR;
case http2::Http2DecoderAdapter::SPDY_UNEXPECTED_FRAME:
return ERR_HTTP2_PROTOCOL_ERROR;
case http2::Http2DecoderAdapter::SPDY_INTERNAL_FRAMER_ERROR:
return ERR_HTTP2_PROTOCOL_ERROR;
case http2::Http2DecoderAdapter::SPDY_INVALID_CONTROL_FRAME_SIZE:
return ERR_HTTP2_FRAME_SIZE_ERROR;
case http2::Http2DecoderAdapter::SPDY_INVALID_STREAM_ID:
return ERR_HTTP2_PROTOCOL_ERROR;
case http2::Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD:
return ERR_HTTP2_FRAME_SIZE_ERROR;
case http2::Http2DecoderAdapter::LAST_ERROR:
NOTREACHED();
}
NOTREACHED();
return ERR_HTTP2_PROTOCOL_ERROR;
}
SpdyProtocolErrorDetails MapRstStreamStatusToProtocolError(
spdy::SpdyErrorCode error_code) {
switch (error_code) {
case spdy::ERROR_CODE_NO_ERROR:
return STATUS_CODE_NO_ERROR;
case spdy::ERROR_CODE_PROTOCOL_ERROR:
return STATUS_CODE_PROTOCOL_ERROR;
case spdy::ERROR_CODE_INTERNAL_ERROR:
return STATUS_CODE_INTERNAL_ERROR;
case spdy::ERROR_CODE_FLOW_CONTROL_ERROR:
return STATUS_CODE_FLOW_CONTROL_ERROR;
case spdy::ERROR_CODE_SETTINGS_TIMEOUT:
return STATUS_CODE_SETTINGS_TIMEOUT;
case spdy::ERROR_CODE_STREAM_CLOSED:
return STATUS_CODE_STREAM_CLOSED;
case spdy::ERROR_CODE_FRAME_SIZE_ERROR:
return STATUS_CODE_FRAME_SIZE_ERROR;
case spdy::ERROR_CODE_REFUSED_STREAM:
return STATUS_CODE_REFUSED_STREAM;
case spdy::ERROR_CODE_CANCEL:
return STATUS_CODE_CANCEL;
case spdy::ERROR_CODE_COMPRESSION_ERROR:
return STATUS_CODE_COMPRESSION_ERROR;
case spdy::ERROR_CODE_CONNECT_ERROR:
return STATUS_CODE_CONNECT_ERROR;
case spdy::ERROR_CODE_ENHANCE_YOUR_CALM:
return STATUS_CODE_ENHANCE_YOUR_CALM;
case spdy::ERROR_CODE_INADEQUATE_SECURITY:
return STATUS_CODE_INADEQUATE_SECURITY;
case spdy::ERROR_CODE_HTTP_1_1_REQUIRED:
return STATUS_CODE_HTTP_1_1_REQUIRED;
}
NOTREACHED();
return static_cast<SpdyProtocolErrorDetails>(-1);
}
spdy::SpdyErrorCode MapNetErrorToGoAwayStatus(Error err) {
switch (err) {
case OK:
return spdy::ERROR_CODE_NO_ERROR;
case ERR_HTTP2_PROTOCOL_ERROR:
return spdy::ERROR_CODE_PROTOCOL_ERROR;
case ERR_HTTP2_FLOW_CONTROL_ERROR:
return spdy::ERROR_CODE_FLOW_CONTROL_ERROR;
case ERR_HTTP2_FRAME_SIZE_ERROR:
return spdy::ERROR_CODE_FRAME_SIZE_ERROR;
case ERR_HTTP2_COMPRESSION_ERROR:
return spdy::ERROR_CODE_COMPRESSION_ERROR;
case ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY:
return spdy::ERROR_CODE_INADEQUATE_SECURITY;
default:
return spdy::ERROR_CODE_PROTOCOL_ERROR;
}
}
SpdyStreamRequest::SpdyStreamRequest() {
Reset();
}
SpdyStreamRequest::~SpdyStreamRequest() {
CancelRequest();
}
int SpdyStreamRequest::StartRequest(
SpdyStreamType type,
const base::WeakPtr<SpdySession>& session,
const GURL& url,
bool can_send_early,
RequestPriority priority,
const SocketTag& socket_tag,
const NetLogWithSource& net_log,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation,
bool detect_broken_connection,
base::TimeDelta heartbeat_interval) {
DCHECK(session);
DCHECK(!session_);
DCHECK(!stream_);
DCHECK(callback_.is_null());
DCHECK(url.is_valid()) << url.possibly_invalid_spec();
type_ = type;
session_ = session;
url_ = SimplifyUrlForRequest(url);
priority_ = priority;
socket_tag_ = socket_tag;
net_log_ = net_log;
callback_ = std::move(callback);
traffic_annotation_ = MutableNetworkTrafficAnnotationTag(traffic_annotation);
detect_broken_connection_ = detect_broken_connection;
heartbeat_interval_ = heartbeat_interval;
// If early data is not allowed, confirm the handshake first.
int rv = OK;
if (!can_send_early) {
rv = session_->ConfirmHandshake(
base::BindOnce(&SpdyStreamRequest::OnConfirmHandshakeComplete,
weak_ptr_factory_.GetWeakPtr()));
}
if (rv != OK) {
// If rv is ERR_IO_PENDING, OnConfirmHandshakeComplete() will call
// TryCreateStream() later.
return rv;
}
base::WeakPtr<SpdyStream> stream;
rv = session->TryCreateStream(weak_ptr_factory_.GetWeakPtr(), &stream);
if (rv != OK) {
// If rv is ERR_IO_PENDING, the SpdySession will call
// OnRequestCompleteSuccess() or OnRequestCompleteFailure() later.
return rv;
}
Reset();
stream_ = stream;
return OK;
}
void SpdyStreamRequest::CancelRequest() {
if (session_)
session_->CancelStreamRequest(weak_ptr_factory_.GetWeakPtr());
Reset();
// Do this to cancel any pending CompleteStreamRequest() and
// OnConfirmHandshakeComplete() tasks.
weak_ptr_factory_.InvalidateWeakPtrs();
}
base::WeakPtr<SpdyStream> SpdyStreamRequest::ReleaseStream() {
DCHECK(!session_);
base::WeakPtr<SpdyStream> stream = stream_;
DCHECK(stream);
Reset();
return stream;
}
void SpdyStreamRequest::SetPriority(RequestPriority priority) {
if (priority_ == priority)
return;
if (stream_)
stream_->SetPriority(priority);
if (session_)
session_->ChangeStreamRequestPriority(weak_ptr_factory_.GetWeakPtr(),
priority);
priority_ = priority;
}
void SpdyStreamRequest::OnRequestCompleteSuccess(
const base::WeakPtr<SpdyStream>& stream) {
DCHECK(session_);
DCHECK(!stream_);
DCHECK(!callback_.is_null());
CompletionOnceCallback callback = std::move(callback_);
Reset();
DCHECK(stream);
stream_ = stream;
std::move(callback).Run(OK);
}
void SpdyStreamRequest::OnRequestCompleteFailure(int rv) {
DCHECK(session_);
DCHECK(!stream_);
DCHECK(!callback_.is_null());
CompletionOnceCallback callback = std::move(callback_);
Reset();
DCHECK_NE(rv, OK);
std::move(callback).Run(rv);
}
void SpdyStreamRequest::Reset() {
type_ = SPDY_BIDIRECTIONAL_STREAM;
session_.reset();
stream_.reset();
url_ = GURL();
priority_ = MINIMUM_PRIORITY;
socket_tag_ = SocketTag();
net_log_ = NetLogWithSource();
callback_.Reset();
traffic_annotation_.reset();
}
void SpdyStreamRequest::OnConfirmHandshakeComplete(int rv) {
DCHECK_NE(ERR_IO_PENDING, rv);
if (!session_)
return;
if (rv != OK) {
OnRequestCompleteFailure(rv);
return;
}
// ConfirmHandshake() completed asynchronously. Record the time so the caller
// can adjust LoadTimingInfo.
confirm_handshake_end_ = base::TimeTicks::Now();
if (!session_) {
OnRequestCompleteFailure(ERR_CONNECTION_CLOSED);
return;
}
base::WeakPtr<SpdyStream> stream;
rv = session_->TryCreateStream(weak_ptr_factory_.GetWeakPtr(), &stream);
if (rv == OK) {
OnRequestCompleteSuccess(stream);
} else if (rv != ERR_IO_PENDING) {
// If rv is ERR_IO_PENDING, the SpdySession will call
// OnRequestCompleteSuccess() or OnRequestCompleteFailure() later.
OnRequestCompleteFailure(rv);
}
}
// static
bool SpdySession::CanPool(
TransportSecurityState* transport_security_state,
const SSLInfo& ssl_info,
const SSLConfigService& ssl_config_service,
const std::string& old_hostname,
const std::string& new_hostname,
const net::NetworkAnonymizationKey& network_anonymization_key) {
// Pooling is prohibited if the server cert is not valid for the new domain,
// and for connections on which client certs were sent. It is also prohibited
// when channel ID was sent if the hosts are from different eTLDs+1.
if (IsCertStatusError(ssl_info.cert_status))
return false;
if (ssl_info.client_cert_sent &&
!(ssl_config_service.CanShareConnectionWithClientCerts(old_hostname) &&
ssl_config_service.CanShareConnectionWithClientCerts(new_hostname))) {
return false;
}
if (!ssl_info.cert->VerifyNameMatch(new_hostname))
return false;
std::string pinning_failure_log;
// DISABLE_PIN_REPORTS is set here because this check can fail in
// normal operation without being indicative of a misconfiguration or
// attack. Port is left at 0 as it is never used.
if (transport_security_state->CheckPublicKeyPins(
HostPortPair(new_hostname, 0), ssl_info.is_issued_by_known_root,
ssl_info.public_key_hashes, ssl_info.unverified_cert.get(),
ssl_info.cert.get(), TransportSecurityState::DISABLE_PIN_REPORTS,
network_anonymization_key, &pinning_failure_log) ==
TransportSecurityState::PKPStatus::VIOLATED) {
return false;
}
switch (transport_security_state->CheckCTRequirements(
HostPortPair(new_hostname, 0), ssl_info.is_issued_by_known_root,
ssl_info.public_key_hashes, ssl_info.cert.get(),
ssl_info.unverified_cert.get(), ssl_info.signed_certificate_timestamps,
ssl_info.ct_policy_compliance)) {
case TransportSecurityState::CT_REQUIREMENTS_NOT_MET:
return false;
case TransportSecurityState::CT_REQUIREMENTS_MET:
case TransportSecurityState::CT_NOT_REQUIRED:
// Intentional fallthrough; this case is just here to make sure that all
// possible values of CheckCTRequirements() are handled.
break;
}
return true;
}
SpdySession::SpdySession(
const SpdySessionKey& spdy_session_key,
HttpServerProperties* http_server_properties,
TransportSecurityState* transport_security_state,
SSLConfigService* ssl_config_service,
const quic::ParsedQuicVersionVector& quic_supported_versions,
bool enable_sending_initial_data,
bool enable_ping_based_connection_checking,
bool is_http2_enabled,
bool is_quic_enabled,
size_t session_max_recv_window_size,
int session_max_queued_capped_frames,
const spdy::SettingsMap& initial_settings,
bool enable_http2_settings_grease,
const absl::optional<SpdySessionPool::GreasedHttp2Frame>&
greased_http2_frame,
bool http2_end_stream_with_data_frame,
bool enable_priority_update,
TimeFunc time_func,
ServerPushDelegate* push_delegate,
NetworkQualityEstimator* network_quality_estimator,
NetLog* net_log)
: spdy_session_key_(spdy_session_key),
http_server_properties_(http_server_properties),
transport_security_state_(transport_security_state),
ssl_config_service_(ssl_config_service),
stream_hi_water_mark_(kFirstStreamId),
push_delegate_(push_delegate),
initial_settings_(initial_settings),
enable_http2_settings_grease_(enable_http2_settings_grease),
greased_http2_frame_(greased_http2_frame),
http2_end_stream_with_data_frame_(http2_end_stream_with_data_frame),
enable_priority_update_(enable_priority_update),
max_concurrent_streams_(kInitialMaxConcurrentStreams),
max_concurrent_pushed_streams_(
initial_settings.at(spdy::SETTINGS_MAX_CONCURRENT_STREAMS)),
last_read_time_(time_func()),
session_max_recv_window_size_(session_max_recv_window_size),
session_max_queued_capped_frames_(session_max_queued_capped_frames),
last_recv_window_update_(base::TimeTicks::Now()),
time_to_buffer_small_window_updates_(
kDefaultTimeToBufferSmallWindowUpdates),
stream_initial_send_window_size_(kDefaultInitialWindowSize),
max_header_table_size_(
initial_settings.at(spdy::SETTINGS_HEADER_TABLE_SIZE)),
stream_max_recv_window_size_(
initial_settings.at(spdy::SETTINGS_INITIAL_WINDOW_SIZE)),
net_log_(
NetLogWithSource::Make(net_log, NetLogSourceType::HTTP2_SESSION)),
quic_supported_versions_(quic_supported_versions),
enable_sending_initial_data_(enable_sending_initial_data),
enable_ping_based_connection_checking_(
enable_ping_based_connection_checking),
is_http2_enabled_(is_http2_enabled),
is_quic_enabled_(is_quic_enabled),
enable_push_(IsPushEnabled(initial_settings)),
connection_at_risk_of_loss_time_(
base::Seconds(kDefaultConnectionAtRiskOfLossSeconds)),
hung_interval_(base::Seconds(kHungIntervalSeconds)),
time_func_(time_func),
network_quality_estimator_(network_quality_estimator) {
net_log_.BeginEvent(NetLogEventType::HTTP2_SESSION, [&] {
return NetLogSpdySessionParams(host_port_proxy_pair());
});
DCHECK(base::Contains(initial_settings_, spdy::SETTINGS_HEADER_TABLE_SIZE));
DCHECK(
base::Contains(initial_settings_, spdy::SETTINGS_MAX_CONCURRENT_STREAMS));
DCHECK(base::Contains(initial_settings_, spdy::SETTINGS_INITIAL_WINDOW_SIZE));
if (greased_http2_frame_) {
// See https://tools.ietf.org/html/draft-bishop-httpbis-grease-00
// for reserved frame types.
DCHECK_EQ(0x0b, greased_http2_frame_.value().type % 0x1f);
}
// TODO(mbelshe): consider randomization of the stream_hi_water_mark.
}
SpdySession::~SpdySession() {
CHECK(!in_io_loop_);
DcheckDraining();
DCHECK(waiting_for_confirmation_callbacks_.empty());
DCHECK_EQ(broken_connection_detection_requests_, 0);
// TODO(akalin): Check connection->is_initialized().
DCHECK(socket_);
// With SPDY we can't recycle sockets.
socket_->Disconnect();
RecordHistograms();
net_log_.EndEvent(NetLogEventType::HTTP2_SESSION);
}
int SpdySession::GetPushedStream(const GURL& url,
spdy::SpdyStreamId pushed_stream_id,
RequestPriority priority,
SpdyStream** stream) {
CHECK(!in_io_loop_);
// |pushed_stream_id| must be valid.