forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspdy_session.cc
3324 lines (2860 loc) · 115 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 (c) 2012 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/spdy/spdy_session.h"
#include <algorithm>
#include <limits>
#include <map>
#include <utility>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "crypto/ec_private_key.h"
#include "crypto/ec_signature_creator.h"
#include "net/base/connection_type_histograms.h"
#include "net/base/proxy_delegate.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_verify_result.h"
#include "net/http/http_log_util.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties.h"
#include "net/http/http_util.h"
#include "net/http/transport_security_state.h"
#include "net/log/net_log.h"
#include "net/proxy/proxy_server.h"
#include "net/socket/ssl_client_socket.h"
#include "net/spdy/spdy_buffer_producer.h"
#include "net/spdy/spdy_frame_builder.h"
#include "net/spdy/spdy_http_utils.h"
#include "net/spdy/spdy_protocol.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/spdy/spdy_stream.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/ssl_cipher_suite_names.h"
#include "net/ssl/ssl_connection_status_flags.h"
namespace net {
namespace {
const int kReadBufferSize = 8 * 1024;
const int kDefaultConnectionAtRiskOfLossSeconds = 10;
const int kHungIntervalSeconds = 10;
// Minimum seconds that unclaimed pushed streams will be kept in memory.
const int kMinPushedStreamLifetimeSeconds = 300;
std::unique_ptr<base::Value> NetLogSpdySynStreamSentCallback(
const SpdyHeaderBlock* headers,
bool fin,
bool unidirectional,
SpdyPriority spdy_priority,
SpdyStreamId stream_id,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->Set("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode));
dict->SetBoolean("fin", fin);
dict->SetBoolean("unidirectional", unidirectional);
dict->SetInteger("priority", static_cast<int>(spdy_priority));
dict->SetInteger("stream_id", stream_id);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyHeadersSentCallback(
const SpdyHeaderBlock* headers,
bool fin,
SpdyStreamId stream_id,
bool has_priority,
uint32_t priority,
SpdyStreamId parent_stream_id,
bool exclusive,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->Set("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode));
dict->SetBoolean("fin", fin);
dict->SetInteger("stream_id", stream_id);
dict->SetBoolean("has_priority", has_priority);
if (has_priority) {
dict->SetInteger("parent_stream_id", parent_stream_id);
dict->SetInteger("priority", static_cast<int>(priority));
dict->SetBoolean("exclusive", exclusive);
}
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySynStreamReceivedCallback(
const SpdyHeaderBlock* headers,
bool fin,
bool unidirectional,
SpdyPriority spdy_priority,
SpdyStreamId stream_id,
SpdyStreamId associated_stream,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->Set("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode));
dict->SetBoolean("fin", fin);
dict->SetBoolean("unidirectional", unidirectional);
dict->SetInteger("priority", static_cast<int>(spdy_priority));
dict->SetInteger("stream_id", stream_id);
dict->SetInteger("associated_stream", associated_stream);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySynReplyOrHeadersReceivedCallback(
const SpdyHeaderBlock* headers,
bool fin,
SpdyStreamId stream_id,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->Set("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode));
dict->SetBoolean("fin", fin);
dict->SetInteger("stream_id", stream_id);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySessionCloseCallback(
int net_error,
const std::string* description,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("net_error", net_error);
dict->SetString("description", *description);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySessionCallback(
const HostPortProxyPair* host_pair,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetString("host", host_pair->first.ToString());
dict->SetString("proxy", host_pair->second.ToPacString());
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyInitializedCallback(
NetLog::Source source,
const NextProto protocol_version,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
if (source.IsValid()) {
source.AddToEventParameters(dict.get());
}
dict->SetString("protocol",
SSLClientSocket::NextProtoToString(protocol_version));
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySettingsCallback(
const HostPortPair& host_port_pair,
bool clear_persisted,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetString("host", host_port_pair.ToString());
dict->SetBoolean("clear_persisted", clear_persisted);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySettingCallback(
SpdySettingsIds id,
const SpdyMajorVersion protocol_version,
SpdySettingsFlags flags,
uint32_t value,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("id",
SpdyConstants::SerializeSettingId(protocol_version, id));
dict->SetInteger("flags", flags);
dict->SetInteger("value", value);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySendSettingsCallback(
const SettingsMap* settings,
const SpdyMajorVersion protocol_version,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
std::unique_ptr<base::ListValue> settings_list(new base::ListValue());
for (SettingsMap::const_iterator it = settings->begin();
it != settings->end(); ++it) {
const SpdySettingsIds id = it->first;
const SpdySettingsFlags flags = it->second.first;
const uint32_t value = it->second.second;
settings_list->Append(new base::StringValue(base::StringPrintf(
"[id:%u flags:%u value:%u]",
SpdyConstants::SerializeSettingId(protocol_version, id),
flags,
value)));
}
dict->Set("settings", std::move(settings_list));
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyWindowUpdateFrameCallback(
SpdyStreamId stream_id,
uint32_t delta,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("stream_id", static_cast<int>(stream_id));
dict->SetInteger("delta", delta);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdySessionWindowUpdateCallback(
int32_t delta,
int32_t window_size,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("delta", delta);
dict->SetInteger("window_size", window_size);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyDataCallback(
SpdyStreamId stream_id,
int size,
bool fin,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("stream_id", static_cast<int>(stream_id));
dict->SetInteger("size", size);
dict->SetBoolean("fin", fin);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyRstCallback(
SpdyStreamId stream_id,
int status,
const std::string* description,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("stream_id", static_cast<int>(stream_id));
dict->SetInteger("status", status);
dict->SetString("description", *description);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyPingCallback(
SpdyPingId unique_id,
bool is_ack,
const char* type,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("unique_id", static_cast<int>(unique_id));
dict->SetString("type", type);
dict->SetBoolean("is_ack", is_ack);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyGoAwayCallback(
SpdyStreamId last_stream_id,
int active_streams,
int unclaimed_streams,
SpdyGoAwayStatus status,
base::StringPiece debug_data,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("last_accepted_stream_id",
static_cast<int>(last_stream_id));
dict->SetInteger("active_streams", active_streams);
dict->SetInteger("unclaimed_streams", unclaimed_streams);
dict->SetInteger("status", static_cast<int>(status));
dict->SetString("debug_data",
ElideGoAwayDebugDataForNetLog(capture_mode, debug_data));
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyPushPromiseReceivedCallback(
const SpdyHeaderBlock* headers,
SpdyStreamId stream_id,
SpdyStreamId promised_stream_id,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->Set("headers", ElideSpdyHeaderBlockForNetLog(*headers, capture_mode));
dict->SetInteger("id", stream_id);
dict->SetInteger("promised_stream_id", promised_stream_id);
return std::move(dict);
}
std::unique_ptr<base::Value> NetLogSpdyAdoptedPushStreamCallback(
SpdyStreamId stream_id,
const GURL* url,
NetLogCaptureMode capture_mode) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("stream_id", stream_id);
dict->SetString("url", url->spec());
return 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;
}
// Helper class for std:find_if on STL container containing
// SpdyStreamRequest weak pointers.
class RequestEquals {
public:
explicit RequestEquals(const base::WeakPtr<SpdyStreamRequest>& request)
: request_(request) {}
bool operator()(const base::WeakPtr<SpdyStreamRequest>& request) const {
return request_.get() == request.get();
}
private:
const base::WeakPtr<SpdyStreamRequest> request_;
};
// 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;
} // namespace
SpdyProtocolErrorDetails MapFramerErrorToProtocolError(
SpdyFramer::SpdyError err) {
switch (err) {
case SpdyFramer::SPDY_NO_ERROR:
return SPDY_ERROR_NO_ERROR;
case SpdyFramer::SPDY_INVALID_CONTROL_FRAME:
return SPDY_ERROR_INVALID_CONTROL_FRAME;
case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
return SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE;
case SpdyFramer::SPDY_ZLIB_INIT_FAILURE:
return SPDY_ERROR_ZLIB_INIT_FAILURE;
case SpdyFramer::SPDY_UNSUPPORTED_VERSION:
return SPDY_ERROR_UNSUPPORTED_VERSION;
case SpdyFramer::SPDY_DECOMPRESS_FAILURE:
return SPDY_ERROR_DECOMPRESS_FAILURE;
case SpdyFramer::SPDY_COMPRESS_FAILURE:
return SPDY_ERROR_COMPRESS_FAILURE;
case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT:
return SPDY_ERROR_GOAWAY_FRAME_CORRUPT;
case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT:
return SPDY_ERROR_RST_STREAM_FRAME_CORRUPT;
case SpdyFramer::SPDY_INVALID_PADDING:
return SPDY_ERROR_INVALID_PADDING;
case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS:
return SPDY_ERROR_INVALID_DATA_FRAME_FLAGS;
case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS:
return SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS;
case SpdyFramer::SPDY_UNEXPECTED_FRAME:
return SPDY_ERROR_UNEXPECTED_FRAME;
case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_SIZE:
return SPDY_ERROR_INVALID_CONTROL_FRAME_SIZE;
case SpdyFramer::SPDY_INVALID_STREAM_ID:
return SPDY_ERROR_INVALID_STREAM_ID;
default:
NOTREACHED();
return static_cast<SpdyProtocolErrorDetails>(-1);
}
}
Error MapFramerErrorToNetError(SpdyFramer::SpdyError err) {
switch (err) {
case SpdyFramer::SPDY_NO_ERROR:
return OK;
case SpdyFramer::SPDY_INVALID_CONTROL_FRAME:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
return ERR_SPDY_FRAME_SIZE_ERROR;
case SpdyFramer::SPDY_ZLIB_INIT_FAILURE:
return ERR_SPDY_COMPRESSION_ERROR;
case SpdyFramer::SPDY_UNSUPPORTED_VERSION:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_DECOMPRESS_FAILURE:
return ERR_SPDY_COMPRESSION_ERROR;
case SpdyFramer::SPDY_COMPRESS_FAILURE:
return ERR_SPDY_COMPRESSION_ERROR;
case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_INVALID_PADDING:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_UNEXPECTED_FRAME:
return ERR_SPDY_PROTOCOL_ERROR;
case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_SIZE:
return ERR_SPDY_FRAME_SIZE_ERROR;
case SpdyFramer::SPDY_INVALID_STREAM_ID:
return ERR_SPDY_PROTOCOL_ERROR;
default:
NOTREACHED();
return ERR_SPDY_PROTOCOL_ERROR;
}
}
SpdyProtocolErrorDetails MapRstStreamStatusToProtocolError(
SpdyRstStreamStatus status) {
switch (status) {
case RST_STREAM_PROTOCOL_ERROR:
return STATUS_CODE_PROTOCOL_ERROR;
case RST_STREAM_INVALID_STREAM:
return STATUS_CODE_INVALID_STREAM;
case RST_STREAM_REFUSED_STREAM:
return STATUS_CODE_REFUSED_STREAM;
case RST_STREAM_UNSUPPORTED_VERSION:
return STATUS_CODE_UNSUPPORTED_VERSION;
case RST_STREAM_CANCEL:
return STATUS_CODE_CANCEL;
case RST_STREAM_INTERNAL_ERROR:
return STATUS_CODE_INTERNAL_ERROR;
case RST_STREAM_FLOW_CONTROL_ERROR:
return STATUS_CODE_FLOW_CONTROL_ERROR;
case RST_STREAM_STREAM_IN_USE:
return STATUS_CODE_STREAM_IN_USE;
case RST_STREAM_STREAM_ALREADY_CLOSED:
return STATUS_CODE_STREAM_ALREADY_CLOSED;
case RST_STREAM_FRAME_SIZE_ERROR:
return STATUS_CODE_FRAME_SIZE_ERROR;
case RST_STREAM_SETTINGS_TIMEOUT:
return STATUS_CODE_SETTINGS_TIMEOUT;
case RST_STREAM_CONNECT_ERROR:
return STATUS_CODE_CONNECT_ERROR;
case RST_STREAM_ENHANCE_YOUR_CALM:
return STATUS_CODE_ENHANCE_YOUR_CALM;
case RST_STREAM_INADEQUATE_SECURITY:
return STATUS_CODE_INADEQUATE_SECURITY;
case RST_STREAM_HTTP_1_1_REQUIRED:
return STATUS_CODE_HTTP_1_1_REQUIRED;
default:
NOTREACHED();
return static_cast<SpdyProtocolErrorDetails>(-1);
}
}
SpdyGoAwayStatus MapNetErrorToGoAwayStatus(Error err) {
switch (err) {
case OK:
return GOAWAY_NO_ERROR;
case ERR_SPDY_PROTOCOL_ERROR:
return GOAWAY_PROTOCOL_ERROR;
case ERR_SPDY_FLOW_CONTROL_ERROR:
return GOAWAY_FLOW_CONTROL_ERROR;
case ERR_SPDY_FRAME_SIZE_ERROR:
return GOAWAY_FRAME_SIZE_ERROR;
case ERR_SPDY_COMPRESSION_ERROR:
return GOAWAY_COMPRESSION_ERROR;
case ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY:
return GOAWAY_INADEQUATE_SECURITY;
default:
return GOAWAY_PROTOCOL_ERROR;
}
}
void SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock& headers,
SpdyMajorVersion protocol_version,
SpdyHeaderBlock* request_headers,
SpdyHeaderBlock* response_headers) {
DCHECK(response_headers);
DCHECK(request_headers);
for (SpdyHeaderBlock::const_iterator it = headers.begin();
it != headers.end();
++it) {
SpdyHeaderBlock* to_insert = response_headers;
const char* host = protocol_version >= HTTP2 ? ":authority" : ":host";
static const char scheme[] = ":scheme";
static const char path[] = ":path";
if (it->first == host || it->first == scheme || it->first == path) {
to_insert = request_headers;
}
to_insert->insert(*it);
}
}
SpdyStreamRequest::SpdyStreamRequest() : weak_ptr_factory_(this) {
Reset();
}
SpdyStreamRequest::~SpdyStreamRequest() {
CancelRequest();
}
int SpdyStreamRequest::StartRequest(
SpdyStreamType type,
const base::WeakPtr<SpdySession>& session,
const GURL& url,
RequestPriority priority,
const BoundNetLog& net_log,
const CompletionCallback& callback) {
DCHECK(session);
DCHECK(!session_);
DCHECK(!stream_);
DCHECK(callback_.is_null());
type_ = type;
session_ = session;
url_ = url;
priority_ = priority;
net_log_ = net_log;
callback_ = callback;
base::WeakPtr<SpdyStream> stream;
int rv = session->TryCreateStream(weak_ptr_factory_.GetWeakPtr(), &stream);
if (rv == OK) {
Reset();
stream_ = stream;
}
return rv;
}
void SpdyStreamRequest::CancelRequest() {
if (session_)
session_->CancelStreamRequest(weak_ptr_factory_.GetWeakPtr());
Reset();
// Do this to cancel any pending CompleteStreamRequest() tasks.
weak_ptr_factory_.InvalidateWeakPtrs();
}
base::WeakPtr<SpdyStream> SpdyStreamRequest::ReleaseStream() {
DCHECK(!session_);
base::WeakPtr<SpdyStream> stream = stream_;
DCHECK(stream);
Reset();
return stream;
}
void SpdyStreamRequest::OnRequestCompleteSuccess(
const base::WeakPtr<SpdyStream>& stream) {
DCHECK(session_);
DCHECK(!stream_);
DCHECK(!callback_.is_null());
CompletionCallback callback = callback_;
Reset();
DCHECK(stream);
stream_ = stream;
callback.Run(OK);
}
void SpdyStreamRequest::OnRequestCompleteFailure(int rv) {
DCHECK(session_);
DCHECK(!stream_);
DCHECK(!callback_.is_null());
CompletionCallback callback = callback_;
Reset();
DCHECK_NE(rv, OK);
callback.Run(rv);
}
void SpdyStreamRequest::Reset() {
type_ = SPDY_BIDIRECTIONAL_STREAM;
session_.reset();
stream_.reset();
url_ = GURL();
priority_ = MINIMUM_PRIORITY;
net_log_ = BoundNetLog();
callback_.Reset();
}
SpdySession::ActiveStreamInfo::ActiveStreamInfo()
: stream(NULL),
waiting_for_syn_reply(false) {}
SpdySession::ActiveStreamInfo::ActiveStreamInfo(SpdyStream* stream)
: stream(stream),
waiting_for_syn_reply(stream->type() != SPDY_PUSH_STREAM) {
}
SpdySession::ActiveStreamInfo::~ActiveStreamInfo() {}
SpdySession::UnclaimedPushedStreamContainer::UnclaimedPushedStreamContainer(
SpdySession* spdy_session)
: spdy_session_(spdy_session) {}
SpdySession::UnclaimedPushedStreamContainer::~UnclaimedPushedStreamContainer() {
}
size_t SpdySession::UnclaimedPushedStreamContainer::erase(const GURL& url) {
const_iterator it = find(url);
if (it != end()) {
streams_.erase(it);
return 1;
}
return 0;
}
SpdySession::UnclaimedPushedStreamContainer::iterator
SpdySession::UnclaimedPushedStreamContainer::erase(const_iterator it) {
DCHECK(spdy_session_->pool_);
DCHECK(it != end());
// Only allow cross-origin push for secure resources.
if (it->first.SchemeIsCryptographic()) {
spdy_session_->pool_->UnregisterUnclaimedPushedStream(it->first,
spdy_session_);
}
return streams_.erase(it);
}
SpdySession::UnclaimedPushedStreamContainer::iterator
SpdySession::UnclaimedPushedStreamContainer::insert(
const_iterator position,
const GURL& url,
SpdyStreamId stream_id,
const base::TimeTicks& creation_time) {
DCHECK(spdy_session_->pool_);
// Only allow cross-origin push for https resources.
if (url.SchemeIsCryptographic()) {
spdy_session_->pool_->RegisterUnclaimedPushedStream(
url, spdy_session_->GetWeakPtr());
}
return streams_.insert(
position,
std::make_pair(
url, SpdySession::UnclaimedPushedStreamContainer::PushedStreamInfo(
stream_id, creation_time)));
}
// static
bool SpdySession::CanPool(TransportSecurityState* transport_security_state,
const SSLInfo& ssl_info,
const std::string& old_hostname,
const std::string& new_hostname) {
// 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)
return false;
if (ssl_info.channel_id_sent &&
ChannelIDService::GetDomainForHost(new_hostname) !=
ChannelIDService::GetDomainForHost(old_hostname)) {
return false;
}
bool unused = false;
if (!ssl_info.cert->VerifyNameMatch(new_hostname, &unused))
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,
&pinning_failure_log)) {
return false;
}
return true;
}
SpdySession::SpdySession(
const SpdySessionKey& spdy_session_key,
const base::WeakPtr<HttpServerProperties>& http_server_properties,
TransportSecurityState* transport_security_state,
bool verify_domain_authentication,
bool enable_sending_initial_data,
bool enable_ping_based_connection_checking,
bool enable_priority_dependencies,
NextProto default_protocol,
size_t session_max_recv_window_size,
size_t stream_max_recv_window_size,
TimeFunc time_func,
ProxyDelegate* proxy_delegate,
NetLog* net_log)
: in_io_loop_(false),
spdy_session_key_(spdy_session_key),
pool_(NULL),
http_server_properties_(http_server_properties),
transport_security_state_(transport_security_state),
read_buffer_(new IOBuffer(kReadBufferSize)),
stream_hi_water_mark_(kFirstStreamId),
last_accepted_push_stream_id_(0),
unclaimed_pushed_streams_(this),
num_pushed_streams_(0u),
num_active_pushed_streams_(0u),
in_flight_write_frame_type_(DATA),
in_flight_write_frame_size_(0),
is_secure_(false),
certificate_error_code_(OK),
availability_state_(STATE_AVAILABLE),
read_state_(READ_STATE_DO_READ),
write_state_(WRITE_STATE_IDLE),
error_on_close_(OK),
max_concurrent_streams_(kInitialMaxConcurrentStreams),
max_concurrent_pushed_streams_(kMaxConcurrentPushedStreams),
streams_initiated_count_(0),
streams_pushed_count_(0),
streams_pushed_and_claimed_count_(0),
streams_abandoned_count_(0),
total_bytes_received_(0),
sent_settings_(false),
received_settings_(false),
stalled_streams_(0),
pings_in_flight_(0),
next_ping_id_(1),
last_activity_time_(time_func()),
last_compressed_frame_len_(0),
check_ping_status_pending_(false),
send_connection_header_prefix_(false),
session_send_window_size_(0),
session_max_recv_window_size_(session_max_recv_window_size),
session_recv_window_size_(0),
session_unacked_recv_window_bytes_(0),
stream_initial_send_window_size_(
GetDefaultInitialWindowSize(default_protocol)),
stream_max_recv_window_size_(stream_max_recv_window_size),
net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP2_SESSION)),
verify_domain_authentication_(verify_domain_authentication),
enable_sending_initial_data_(enable_sending_initial_data),
enable_ping_based_connection_checking_(
enable_ping_based_connection_checking),
protocol_(default_protocol),
connection_at_risk_of_loss_time_(
base::TimeDelta::FromSeconds(kDefaultConnectionAtRiskOfLossSeconds)),
hung_interval_(base::TimeDelta::FromSeconds(kHungIntervalSeconds)),
proxy_delegate_(proxy_delegate),
time_func_(time_func),
priority_dependencies_enabled_(enable_priority_dependencies),
weak_factory_(this) {
DCHECK_GE(protocol_, kProtoSPDYMinimumVersion);
DCHECK_LE(protocol_, kProtoSPDYMaximumVersion);
DCHECK(HttpStreamFactory::spdy_enabled());
net_log_.BeginEvent(
NetLog::TYPE_HTTP2_SESSION,
base::Bind(&NetLogSpdySessionCallback, &host_port_proxy_pair()));
next_unclaimed_push_stream_sweep_time_ = time_func_() +
base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds);
// TODO(mbelshe): consider randomization of the stream_hi_water_mark.
}
SpdySession::~SpdySession() {
CHECK(!in_io_loop_);
DcheckDraining();
// TODO(akalin): Check connection->is_initialized() instead. This
// requires re-working CreateFakeSpdySession(), though.
DCHECK(connection_->socket());
// With SPDY we can't recycle sockets.
connection_->socket()->Disconnect();
RecordHistograms();
net_log_.EndEvent(NetLog::TYPE_HTTP2_SESSION);
}
void SpdySession::InitializeWithSocket(
std::unique_ptr<ClientSocketHandle> connection,
SpdySessionPool* pool,
bool is_secure,
int certificate_error_code) {
CHECK(!in_io_loop_);
DCHECK_EQ(availability_state_, STATE_AVAILABLE);
DCHECK_EQ(read_state_, READ_STATE_DO_READ);
DCHECK_EQ(write_state_, WRITE_STATE_IDLE);
DCHECK(!connection_);
DCHECK(certificate_error_code == OK ||
certificate_error_code < ERR_IO_PENDING);
// TODO(akalin): Check connection->is_initialized() instead. This
// requires re-working CreateFakeSpdySession(), though.
DCHECK(connection->socket());
connection_ = std::move(connection);
is_secure_ = is_secure;
certificate_error_code_ = certificate_error_code;
NextProto protocol_negotiated =
connection_->socket()->GetNegotiatedProtocol();
if (protocol_negotiated != kProtoUnknown) {
protocol_ = protocol_negotiated;
stream_initial_send_window_size_ = GetDefaultInitialWindowSize(protocol_);
}
DCHECK_GE(protocol_, kProtoSPDYMinimumVersion);
DCHECK_LE(protocol_, kProtoSPDYMaximumVersion);
if (protocol_ == kProtoHTTP2)
send_connection_header_prefix_ = true;
session_send_window_size_ = GetDefaultInitialWindowSize(protocol_);
session_recv_window_size_ = GetDefaultInitialWindowSize(protocol_);
buffered_spdy_framer_.reset(
new BufferedSpdyFramer(NextProtoToSpdyMajorVersion(protocol_)));
buffered_spdy_framer_->set_visitor(this);
buffered_spdy_framer_->set_debug_visitor(this);
UMA_HISTOGRAM_ENUMERATION(
"Net.SpdyVersion3", protocol_ - kProtoSPDYHistogramOffset,
kProtoSPDYMaximumVersion - kProtoSPDYHistogramOffset + 1);
net_log_.AddEvent(
NetLog::TYPE_HTTP2_SESSION_INITIALIZED,
base::Bind(&NetLogSpdyInitializedCallback,
connection_->socket()->NetLog().source(), protocol_));
DCHECK_EQ(availability_state_, STATE_AVAILABLE);
connection_->AddHigherLayeredPool(this);
if (enable_sending_initial_data_)
SendInitialData();
pool_ = pool;
// Bootstrap the read loop.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&SpdySession::PumpReadLoop, weak_factory_.GetWeakPtr(),
READ_STATE_DO_READ, OK));
}
bool SpdySession::VerifyDomainAuthentication(const std::string& domain) {
if (!verify_domain_authentication_)
return true;
if (availability_state_ == STATE_DRAINING)
return false;
SSLInfo ssl_info;
bool was_npn_negotiated;
NextProto protocol_negotiated = kProtoUnknown;
if (!GetSSLInfo(&ssl_info, &was_npn_negotiated, &protocol_negotiated))
return true; // This is not a secure session, so all domains are okay.
return CanPool(transport_security_state_, ssl_info,
host_port_pair().host(), domain);
}
int SpdySession::GetPushStream(
const GURL& url,
base::WeakPtr<SpdyStream>* stream,
const BoundNetLog& stream_net_log) {
CHECK(!in_io_loop_);
stream->reset();
if (availability_state_ == STATE_DRAINING)
return ERR_CONNECTION_CLOSED;
Error err = TryAccessStream(url);
if (err != OK)
return err;
*stream = GetActivePushStream(url);
if (*stream) {
DCHECK_LT(streams_pushed_and_claimed_count_, streams_pushed_count_);
streams_pushed_and_claimed_count_++;
}
return OK;
}
// {,Try}CreateStream() and TryAccessStream() can be called with
// |in_io_loop_| set if a stream is being created in response to
// another being closed due to received data.
Error SpdySession::TryAccessStream(const GURL& url) {
if (is_secure_ && certificate_error_code_ != OK &&
(url.SchemeIs("https") || url.SchemeIs("wss"))) {
RecordProtocolErrorHistogram(
PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION);
DoDrainSession(
static_cast<Error>(certificate_error_code_),
"Tried to get SPDY stream for secure content over an unauthenticated "
"session.");
return ERR_SPDY_PROTOCOL_ERROR;
}
return OK;
}
int SpdySession::TryCreateStream(
const base::WeakPtr<SpdyStreamRequest>& request,
base::WeakPtr<SpdyStream>* stream) {
DCHECK(request);
if (availability_state_ == STATE_GOING_AWAY)
return ERR_FAILED;
if (availability_state_ == STATE_DRAINING)
return ERR_CONNECTION_CLOSED;
Error err = TryAccessStream(request->url());
if (err != OK)
return err;
if ((active_streams_.size() + created_streams_.size() - num_pushed_streams_ <
max_concurrent_streams_)) {
return CreateStream(*request, stream);
}
stalled_streams_++;
net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_STALLED_MAX_STREAMS);
RequestPriority priority = request->priority();
CHECK_GE(priority, MINIMUM_PRIORITY);
CHECK_LE(priority, MAXIMUM_PRIORITY);
pending_create_stream_queues_[priority].push_back(request);
return ERR_IO_PENDING;
}
int SpdySession::CreateStream(const SpdyStreamRequest& request,
base::WeakPtr<SpdyStream>* stream) {
DCHECK_GE(request.priority(), MINIMUM_PRIORITY);
DCHECK_LE(request.priority(), MAXIMUM_PRIORITY);
if (availability_state_ == STATE_GOING_AWAY)
return ERR_FAILED;
if (availability_state_ == STATE_DRAINING)
return ERR_CONNECTION_CLOSED;
Error err = TryAccessStream(request.url());
if (err != OK) {
// This should have been caught in TryCreateStream().
NOTREACHED();
return err;
}
DCHECK(connection_->socket());
UMA_HISTOGRAM_BOOLEAN("Net.SpdySession.CreateStreamWithSocketConnected",
connection_->socket()->IsConnected());
if (!connection_->socket()->IsConnected()) {
DoDrainSession(
ERR_CONNECTION_CLOSED,
"Tried to create SPDY stream for a closed socket connection.");
return ERR_CONNECTION_CLOSED;
}
std::unique_ptr<SpdyStream> new_stream(
new SpdyStream(request.type(), GetWeakPtr(), request.url(),
request.priority(), stream_initial_send_window_size_,
stream_max_recv_window_size_, request.net_log()));
*stream = new_stream->GetWeakPtr();
InsertCreatedStream(std::move(new_stream));
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Net.SpdyPriorityCount",
static_cast<int>(request.priority()), 0, 10, 11);
return OK;
}
void SpdySession::CancelStreamRequest(
const base::WeakPtr<SpdyStreamRequest>& request) {
DCHECK(request);
RequestPriority priority = request->priority();
CHECK_GE(priority, MINIMUM_PRIORITY);
CHECK_LE(priority, MAXIMUM_PRIORITY);
#if DCHECK_IS_ON()
// |request| should not be in a queue not matching its priority.
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
if (priority == i)
continue;
PendingStreamRequestQueue* queue = &pending_create_stream_queues_[i];
DCHECK(std::find_if(queue->begin(),
queue->end(),
RequestEquals(request)) == queue->end());
}
#endif
PendingStreamRequestQueue* queue =
&pending_create_stream_queues_[priority];
// Remove |request| from |queue| while preserving the order of the
// other elements.
PendingStreamRequestQueue::iterator it =
std::find_if(queue->begin(), queue->end(), RequestEquals(request));
// The request may already be removed if there's a
// CompleteStreamRequest() in flight.
if (it != queue->end()) {
it = queue->erase(it);
// |request| should be in the queue at most once, and if it is
// present, should not be pending completion.
DCHECK(std::find_if(it, queue->end(), RequestEquals(request)) ==
queue->end());
}
}
base::WeakPtr<SpdyStreamRequest> SpdySession::GetNextPendingStreamRequest() {
for (int j = MAXIMUM_PRIORITY; j >= MINIMUM_PRIORITY; --j) {
if (pending_create_stream_queues_[j].empty())
continue;
base::WeakPtr<SpdyStreamRequest> pending_request =
pending_create_stream_queues_[j].front();
DCHECK(pending_request);