-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
http_impl.dart
3792 lines (3340 loc) · 115 KB
/
http_impl.dart
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) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of dart._http;
abstract final class HttpProfiler {
static const _kType = 'HttpProfile';
static final Map<String, _HttpProfileData> _profile = {};
static _HttpProfileData? startRequest(
String method,
Uri uri, {
_HttpProfileData? parentRequest,
}) {
if (const bool.fromEnvironment("dart.vm.product")) return null;
final data = _HttpProfileData(method, uri, parentRequest?._timeline);
_profile[data.id] = data;
return data;
}
static _HttpProfileData? getHttpProfileRequest(String id) => _profile[id];
static void clear() => _profile.clear();
/// Returns a list of Maps, where each map conforms to the @HttpProfileRequest
/// type defined in the dart:io service extension spec.
static List<Map<String, dynamic>> serializeHttpProfileRequests(
int? updatedSince) {
return _profile.values
.where(
(e) => (updatedSince == null) || e.lastUpdateTime >= updatedSince,
)
.map((e) => e.toJson(ref: true))
.toList();
}
}
class _HttpProfileEvent {
_HttpProfileEvent(this.name, this.arguments);
final int timestamp = DateTime.now().microsecondsSinceEpoch;
final String name;
final Map? arguments;
Map<String, dynamic> toJson() {
return <String, dynamic>{
'timestamp': timestamp,
'event': name,
if (arguments != null) 'arguments': arguments,
};
}
}
class _HttpProfileData {
_HttpProfileData(String method, this.uri, TimelineTask? parent)
: method = method.toUpperCase(),
_timeline = TimelineTask(
filterKey: 'HTTP/client',
parent: parent,
) {
// Grab the ID from the timeline event so HTTP profile IDs can be matched
// to the timeline.
id = _timeline.pass().toString();
requestInProgress = true;
requestStartTimestamp = DateTime.now().microsecondsSinceEpoch;
_timeline.start('HTTP CLIENT $method', arguments: {
'method': method.toUpperCase(),
'uri': uri.toString(),
});
_updated();
}
void requestEvent(String name, {Map? arguments}) {
_timeline.instant(name, arguments: arguments);
requestEvents.add(_HttpProfileEvent(name, arguments));
_updated();
}
void proxyEvent(_Proxy proxy) {
proxyDetails = {
if (proxy.host != null) 'host': proxy.host,
if (proxy.port != null) 'port': proxy.port,
if (proxy.username != null) 'username': proxy.username,
};
_timeline.instant('Establishing proxy tunnel', arguments: {
'proxyDetails': proxyDetails,
});
_updated();
}
void appendRequestData(Uint8List data) {
requestBody.addAll(data);
_updated();
}
Map formatHeaders(HttpHeaders headers) {
final newHeaders = <String, List<String>>{};
headers.forEach((name, values) {
newHeaders[name] = values;
});
return newHeaders;
}
Map? formatConnectionInfo(HttpConnectionInfo? connectionInfo) =>
connectionInfo == null
? null
: {
'localPort': connectionInfo.localPort,
'remoteAddress': connectionInfo.remoteAddress.address,
'remotePort': connectionInfo.remotePort,
};
void finishRequest({
required HttpClientRequest request,
}) {
// TODO(bkonyi): include encoding?
requestInProgress = false;
requestEndTimestamp = DateTime.now().microsecondsSinceEpoch;
requestDetails = <String, dynamic>{
// TODO(bkonyi): consider exposing certificate information?
// 'certificate': response.certificate,
'headers': formatHeaders(request.headers),
'connectionInfo': formatConnectionInfo(request.connectionInfo),
'contentLength': request.contentLength,
'cookies': [
for (final cookie in request.cookies) cookie.toString(),
],
'followRedirects': request.followRedirects,
'maxRedirects': request.maxRedirects,
'method': request.method,
'persistentConnection': request.persistentConnection,
'uri': request.uri.toString(),
};
_timeline.finish(
arguments: requestDetails,
);
_updated();
}
void startResponse({required HttpClientResponse response}) {
List<Map<String, dynamic>> formatRedirectInfo() {
final redirects = <Map<String, dynamic>>[];
for (final redirect in response.redirects) {
redirects.add({
'location': redirect.location.toString(),
'method': redirect.method,
'statusCode': redirect.statusCode,
});
}
return redirects;
}
responseDetails = <String, dynamic>{
'headers': formatHeaders(response.headers),
'compressionState': response.compressionState.toString(),
'connectionInfo': formatConnectionInfo(response.connectionInfo),
'contentLength': response.contentLength,
'cookies': [
for (final cookie in response.cookies) cookie.toString(),
],
'isRedirect': response.isRedirect,
'persistentConnection': response.persistentConnection,
'reasonPhrase': response.reasonPhrase,
'redirects': formatRedirectInfo(),
'statusCode': response.statusCode,
};
assert(!requestInProgress);
responseInProgress = true;
_responseTimeline = TimelineTask(
parent: _timeline,
filterKey: 'HTTP/client',
);
responseStartTimestamp = DateTime.now().microsecondsSinceEpoch;
_responseTimeline.start(
'HTTP CLIENT response of $method',
arguments: {
'requestUri': uri.toString(),
...responseDetails!,
},
);
_updated();
}
void finishRequestWithError(String error) {
requestInProgress = false;
requestEndTimestamp = DateTime.now().microsecondsSinceEpoch;
requestError = error;
_timeline.finish(arguments: {
'error': error,
});
_updated();
}
void finishResponse() {
responseInProgress = false;
responseEndTimestamp = DateTime.now().microsecondsSinceEpoch;
requestEvent('Content Download');
_responseTimeline.finish();
_updated();
}
void finishResponseWithError(String error) {
// Return if finishResponseWithError has already been called. Can happen if
// the response stream is listened to with `cancelOnError: false`.
if (!responseInProgress!) return;
responseInProgress = false;
responseEndTimestamp = DateTime.now().microsecondsSinceEpoch;
responseError = error;
_responseTimeline.finish(arguments: {
'error': error,
});
_updated();
}
void appendResponseData(Uint8List data) {
responseBody.addAll(data);
_updated();
}
Map<String, dynamic> toJson({required bool ref}) {
return <String, dynamic>{
'type': '${ref ? '@' : ''}HttpProfileRequest',
'id': id,
'isolateId': isolateId,
'method': method,
'uri': uri.toString(),
'events': <Map<String, dynamic>>[
for (final event in requestEvents) event.toJson(),
],
'startTime': requestStartTimestamp,
if (!requestInProgress) 'endTime': requestEndTimestamp,
if (!requestInProgress)
'request': {
if (proxyDetails != null) 'proxyDetails': proxyDetails!,
if (requestDetails != null) ...requestDetails!,
if (requestError != null) 'error': requestError,
},
if (responseInProgress != null)
'response': <String, dynamic>{
'startTime': responseStartTimestamp,
...responseDetails!,
if (!responseInProgress!) 'endTime': responseEndTimestamp,
if (responseError != null) 'error': responseError,
},
if (!ref) ...{
if (!requestInProgress) 'requestBody': requestBody,
if (responseInProgress != null) 'responseBody': responseBody,
}
};
}
void _updated() => _lastUpdateTime = DateTime.now().microsecondsSinceEpoch;
static final String isolateId = Service.getIsolateID(Isolate.current)!;
bool requestInProgress = true;
bool? responseInProgress;
late final String id;
final String method;
final Uri uri;
late final int requestStartTimestamp;
late final int requestEndTimestamp;
Map<String, dynamic>? requestDetails;
Map<String, dynamic>? proxyDetails;
final requestBody = <int>[];
String? requestError;
final requestEvents = <_HttpProfileEvent>[];
late final int responseStartTimestamp;
late final int responseEndTimestamp;
Map<String, dynamic>? responseDetails;
final responseBody = <int>[];
String? responseError;
int get lastUpdateTime => _lastUpdateTime;
int _lastUpdateTime = 0;
final TimelineTask _timeline;
late TimelineTask _responseTimeline;
}
int _nextServiceId = 1;
// TODO(ajohnsen): Use other way of getting a unique id.
mixin _ServiceObject {
int __serviceId = 0;
int get _serviceId {
if (__serviceId == 0) __serviceId = _nextServiceId++;
return __serviceId;
}
String get _servicePath => "$_serviceTypePath/$_serviceId";
String get _serviceTypePath;
String get _serviceTypeName;
String _serviceType(bool ref) {
if (ref) return "@$_serviceTypeName";
return _serviceTypeName;
}
}
class _CopyingBytesBuilder implements BytesBuilder {
// Start with 1024 bytes.
static const int _INIT_SIZE = 1024;
static final _emptyList = Uint8List(0);
int _length = 0;
Uint8List _buffer;
_CopyingBytesBuilder([int initialCapacity = 0])
: _buffer = (initialCapacity <= 0)
? _emptyList
: Uint8List(_pow2roundup(initialCapacity));
void add(List<int> bytes) {
int bytesLength = bytes.length;
if (bytesLength == 0) return;
int required = _length + bytesLength;
if (_buffer.length < required) {
_grow(required);
}
assert(_buffer.length >= required);
if (bytes is Uint8List) {
_buffer.setRange(_length, required, bytes);
} else {
for (int i = 0; i < bytesLength; i++) {
_buffer[_length + i] = bytes[i];
}
}
_length = required;
}
void addByte(int byte) {
if (_buffer.length == _length) {
// The grow algorithm always at least doubles.
// If we added one to _length it would quadruple unnecessarily.
_grow(_length);
}
assert(_buffer.length > _length);
_buffer[_length] = byte;
_length++;
}
void _grow(int required) {
// We will create a list in the range of 2-4 times larger than
// required.
int newSize = required * 2;
if (newSize < _INIT_SIZE) {
newSize = _INIT_SIZE;
} else {
newSize = _pow2roundup(newSize);
}
var newBuffer = Uint8List(newSize);
newBuffer.setRange(0, _buffer.length, _buffer);
_buffer = newBuffer;
}
Uint8List takeBytes() {
if (_length == 0) return _emptyList;
var buffer = Uint8List.view(_buffer.buffer, _buffer.offsetInBytes, _length);
clear();
return buffer;
}
Uint8List toBytes() {
if (_length == 0) return _emptyList;
return Uint8List.fromList(
Uint8List.view(_buffer.buffer, _buffer.offsetInBytes, _length));
}
int get length => _length;
bool get isEmpty => _length == 0;
bool get isNotEmpty => _length != 0;
void clear() {
_length = 0;
_buffer = _emptyList;
}
static int _pow2roundup(int x) {
assert(x > 0);
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
}
const int _OUTGOING_BUFFER_SIZE = 8 * 1024;
typedef _BytesConsumer = void Function(List<int> bytes);
class _HttpIncoming extends Stream<Uint8List> {
final int _transferLength;
final _dataCompleter = Completer<bool>();
final Stream<Uint8List> _stream;
bool fullBodyRead = false;
// Common properties.
final _HttpHeaders headers;
bool upgraded = false;
// ClientResponse properties.
int? statusCode;
String? reasonPhrase;
// Request properties.
String? method;
Uri? uri;
bool hasSubscriber = false;
// The transfer length if the length of the message body as it
// appears in the message (RFC 2616 section 4.4). This can be -1 if
// the length of the massage body is not known due to transfer
// codings.
int get transferLength => _transferLength;
_HttpIncoming(this.headers, this._transferLength, this._stream);
StreamSubscription<Uint8List> listen(void Function(Uint8List event)? onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
hasSubscriber = true;
return _stream.handleError((error) {
throw HttpException((error as HttpException).message, uri: uri);
}, test: (error) => error is HttpException).listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
// Is completed once all data have been received.
Future<bool> get dataDone => _dataCompleter.future;
void close(bool closing) {
fullBodyRead = true;
hasSubscriber = true;
_dataCompleter.complete(closing);
}
}
abstract class _HttpInboundMessageListInt extends Stream<List<int>> {
final _HttpIncoming _incoming;
List<Cookie>? _cookies;
_HttpInboundMessageListInt(this._incoming);
List<Cookie> get cookies => _cookies ??= headers._parseCookies();
_HttpHeaders get headers => _incoming.headers;
String get protocolVersion => headers.protocolVersion;
int get contentLength => headers.contentLength;
bool get persistentConnection => headers.persistentConnection;
}
abstract class _HttpInboundMessage extends Stream<Uint8List> {
final _HttpIncoming _incoming;
List<Cookie>? _cookies;
_HttpInboundMessage(this._incoming);
List<Cookie> get cookies => _cookies ??= headers._parseCookies();
_HttpHeaders get headers => _incoming.headers;
String get protocolVersion => headers.protocolVersion;
int get contentLength => headers.contentLength;
bool get persistentConnection => headers.persistentConnection;
}
class _HttpRequest extends _HttpInboundMessage implements HttpRequest {
final HttpResponse response;
final _HttpServer _httpServer;
final _HttpConnection _httpConnection;
_HttpSession? _session;
Uri? _requestedUri;
_HttpRequest(this.response, _HttpIncoming _incoming, this._httpServer,
this._httpConnection)
: super(_incoming) {
if (headers.protocolVersion == "1.1") {
response.headers
..chunkedTransferEncoding = true
..persistentConnection = headers.persistentConnection;
}
if (_httpServer._sessionManagerInstance != null) {
// Map to session if exists.
var sessionIds = cookies
.where((cookie) => cookie.name.toUpperCase() == _DART_SESSION_ID)
.map<String>((cookie) => cookie.value);
for (var sessionId in sessionIds) {
var session = _httpServer._sessionManager.getSession(sessionId);
_session = session;
if (session != null) {
session._markSeen();
break;
}
}
}
}
StreamSubscription<Uint8List> listen(void Function(Uint8List event)? onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
return _incoming.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
Uri get uri => _incoming.uri!;
Uri get requestedUri {
var requestedUri = _requestedUri;
if (requestedUri != null) return requestedUri;
// `uri` can be an absoluteURI or an abs_path (RFC 2616 section 5.1.2).
// If `uri` is already absolute then use it as-is. Otherwise construct an
// absolute URI using `uri` and header information.
// RFC 3986 section 4.3 says that an absolute URI must have a scheme and
// cannot have a fragment. But any URI with a scheme is sufficient for the
// purpose of providing the `requestedUri`.
if (uri.hasScheme) {
return _requestedUri = uri;
}
var proto = headers['x-forwarded-proto'];
var scheme = proto != null
? proto.first
: _httpConnection._socket is SecureSocket
? "https"
: "http";
var hostList = headers['x-forwarded-host'];
String host;
if (hostList != null) {
host = hostList.first;
} else {
hostList = headers[HttpHeaders.hostHeader];
if (hostList != null) {
host = hostList.first;
} else {
host = "${_httpServer.address.host}:${_httpServer.port}";
}
}
return _requestedUri = Uri.parse("$scheme://$host$uri");
}
String get method => _incoming.method!;
HttpSession get session {
var session = _session;
if (session != null && !session._destroyed) {
return session;
}
// Create session, store it in connection, and return.
return _session = _httpServer._sessionManager.createSession();
}
HttpConnectionInfo? get connectionInfo => _httpConnection.connectionInfo;
X509Certificate? get certificate {
var socket = _httpConnection._socket;
if (socket is SecureSocket) return socket.peerCertificate;
return null;
}
}
class _HttpClientResponse extends _HttpInboundMessageListInt
implements HttpClientResponse {
List<RedirectInfo> get redirects => _httpRequest._responseRedirects;
// The HttpClient this response belongs to.
final _HttpClient _httpClient;
// The HttpClientRequest of this response.
final _HttpClientRequest _httpRequest;
// The compression state of this response.
final HttpClientResponseCompressionState compressionState;
final _HttpProfileData? _profileData;
_HttpClientResponse(_HttpIncoming _incoming, this._httpRequest,
this._httpClient, this._profileData)
: compressionState = _getCompressionState(_httpClient, _incoming.headers),
super(_incoming) {
// Set uri for potential exceptions.
_incoming.uri = _httpRequest.uri;
}
static HttpClientResponseCompressionState _getCompressionState(
_HttpClient httpClient, _HttpHeaders headers) {
if (headers.value(HttpHeaders.contentEncodingHeader) == "gzip") {
return httpClient.autoUncompress
? HttpClientResponseCompressionState.decompressed
: HttpClientResponseCompressionState.compressed;
} else {
return HttpClientResponseCompressionState.notCompressed;
}
}
int get statusCode => _incoming.statusCode!;
String get reasonPhrase => _incoming.reasonPhrase!;
X509Certificate? get certificate {
var socket = _httpRequest._httpClientConnection._socket;
if (socket is SecureSocket) return socket.peerCertificate;
return null;
}
List<Cookie> get cookies {
var cookies = _cookies;
if (cookies != null) return cookies;
cookies = <Cookie>[];
List<String>? values = headers[HttpHeaders.setCookieHeader];
if (values != null) {
for (var value in values) {
cookies.add(Cookie.fromSetCookieValue(value));
}
}
_cookies = cookies;
return cookies;
}
bool get isRedirect {
if (_httpRequest.method == "GET" || _httpRequest.method == "HEAD") {
return statusCode == HttpStatus.movedPermanently ||
statusCode == HttpStatus.permanentRedirect ||
statusCode == HttpStatus.found ||
statusCode == HttpStatus.seeOther ||
statusCode == HttpStatus.temporaryRedirect;
} else if (_httpRequest.method == "POST") {
return statusCode == HttpStatus.seeOther;
}
return false;
}
Future<HttpClientResponse> redirect(
[String? method, Uri? url, bool? followLoops]) {
if (method == null) {
// Set method as defined by RFC 2616 section 10.3.4.
if (statusCode == HttpStatus.seeOther && _httpRequest.method == "POST") {
method = "GET";
} else {
method = _httpRequest.method;
}
}
if (url == null) {
String? location = headers.value(HttpHeaders.locationHeader);
if (location == null) {
throw StateError("Response has no Location header for redirect");
}
url = Uri.parse(location);
}
if (followLoops != true) {
for (var redirect in redirects) {
if (redirect.location == url) {
return Future.error(
RedirectException("Redirect loop detected", redirects));
}
}
}
return _httpClient
._openUrlFromRequest(method, url, _httpRequest, isRedirect: true)
.then((request) {
request._responseRedirects
..addAll(redirects)
..add(_RedirectInfo(statusCode, method!, url!));
return request.close();
});
}
StreamSubscription<Uint8List> listen(void Function(Uint8List event)? onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
if (_incoming.upgraded) {
_profileData?.finishResponseWithError('Connection was upgraded');
// If upgraded, the connection is already 'removed' form the client.
// Since listening to upgraded data is 'bogus', simply close and
// return empty stream subscription.
_httpRequest._httpClientConnection.destroy();
return Stream<Uint8List>.empty().listen(null, onDone: onDone);
}
Stream<Uint8List> stream = _incoming;
if (compressionState == HttpClientResponseCompressionState.decompressed) {
stream = stream
.cast<List<int>>()
.transform(gzip.decoder)
.transform(const _ToUint8List());
}
if (_profileData != null) {
// If _timeline is not set up, don't add unnecessary map() to the stream.
stream = stream.map((data) {
_profileData.appendResponseData(data);
return data;
});
}
return stream.listen(onData, onError: (e, st) {
_profileData?.finishResponseWithError(e.toString());
if (onError == null) {
return;
}
if (onError is void Function(Object, StackTrace)) {
onError(e, st);
} else {
(onError as void Function(Object))(e);
}
}, onDone: () {
_profileData?.finishResponse();
if (onDone != null) {
onDone();
}
}, cancelOnError: cancelOnError);
}
Future<Socket> detachSocket() {
_profileData?.finishResponseWithError('Socket has been detached');
_httpClient._connectionClosed(_httpRequest._httpClientConnection);
return _httpRequest._httpClientConnection.detachSocket();
}
HttpConnectionInfo? get connectionInfo => _httpRequest.connectionInfo;
bool get _shouldAuthenticateProxy {
// Only try to authenticate if there is a challenge in the response.
List<String>? challenge = headers[HttpHeaders.proxyAuthenticateHeader];
return statusCode == HttpStatus.proxyAuthenticationRequired &&
challenge != null &&
challenge.length == 1;
}
bool get _shouldAuthenticate {
// Only try to authenticate if there is a challenge in the response.
List<String>? challenge = headers[HttpHeaders.wwwAuthenticateHeader];
return statusCode == HttpStatus.unauthorized &&
challenge != null &&
challenge.length == 1;
}
Future<HttpClientResponse> _authenticate(bool proxyAuth) {
_httpRequest._profileData?.requestEvent('Authentication');
Future<HttpClientResponse> retry() {
_httpRequest._profileData?.requestEvent('Retrying');
// Drain body and retry.
return drain().then((_) {
return _httpClient
._openUrlFromRequest(
_httpRequest.method, _httpRequest.uri, _httpRequest,
isRedirect: false)
.then((request) => request.close());
});
}
List<String>? authChallenge() {
return proxyAuth
? headers[HttpHeaders.proxyAuthenticateHeader]
: headers[HttpHeaders.wwwAuthenticateHeader];
}
_Credentials? findCredentials(_AuthenticationScheme scheme) {
return proxyAuth
? _httpClient._findProxyCredentials(_httpRequest._proxy, scheme)
: _httpClient._findCredentials(_httpRequest.uri, scheme);
}
void removeCredentials(_Credentials cr) {
if (proxyAuth) {
_httpClient._removeProxyCredentials(cr);
} else {
_httpClient._removeCredentials(cr);
}
}
Future<bool> requestAuthentication(
_AuthenticationScheme scheme, String? realm) {
if (proxyAuth) {
var authenticateProxy = _httpClient._authenticateProxy;
if (authenticateProxy == null) {
return Future.value(false);
}
var proxy = _httpRequest._proxy;
if (!proxy.isDirect) {
return authenticateProxy(
proxy.host!, proxy.port!, scheme.toString(), realm);
}
}
var authenticate = _httpClient._authenticate;
if (authenticate == null) {
return Future.value(false);
}
return authenticate(_httpRequest.uri, scheme.toString(), realm);
}
List<String> challenge = authChallenge()!;
assert(challenge.length == 1);
_HeaderValue header =
_HeaderValue.parse(challenge[0], parameterSeparator: ",");
_AuthenticationScheme scheme =
_AuthenticationScheme.fromString(header.value);
String? realm = header.parameters["realm"];
// See if any matching credentials are available.
var cr = findCredentials(scheme);
if (cr != null) {
// For basic authentication don't retry already used credentials
// as they must have already been added to the request causing
// this authenticate response.
if (cr.scheme == _AuthenticationScheme.BASIC && !cr.used) {
// Credentials were found, prepare for retrying the request.
return retry();
}
// Digest authentication only supports the MD5 algorithm.
if (cr.scheme == _AuthenticationScheme.DIGEST) {
var algorithm = header.parameters["algorithm"];
if (algorithm == null || algorithm.toLowerCase() == "md5") {
var nonce = cr.nonce;
if (nonce == null || nonce == header.parameters["nonce"]) {
// If the nonce is not set then this is the first authenticate
// response for these credentials. Set up authentication state.
if (nonce == null) {
cr
..nonce = header.parameters["nonce"]
..algorithm = "MD5"
..qop = header.parameters["qop"]
..nonceCount = 0;
}
// Credentials were found, prepare for retrying the request.
return retry();
} else {
var staleHeader = header.parameters["stale"];
if (staleHeader != null && staleHeader.toLowerCase() == "true") {
// If stale is true retry with new nonce.
cr.nonce = header.parameters["nonce"];
// Credentials were found, prepare for retrying the request.
return retry();
}
}
}
}
}
// Ask for more credentials if none found or the one found has
// already been used. If it has already been used it must now be
// invalid and is removed.
if (cr != null) {
removeCredentials(cr);
cr = null;
}
return requestAuthentication(scheme, realm).then((credsAvailable) {
if (credsAvailable) {
cr = _httpClient._findCredentials(_httpRequest.uri, scheme);
return retry();
} else {
// No credentials available, complete with original response.
return this;
}
});
}
}
class _ToUint8List extends Converter<List<int>, Uint8List> {
const _ToUint8List();
Uint8List convert(List<int> input) => Uint8List.fromList(input);
Sink<List<int>> startChunkedConversion(Sink<Uint8List> sink) {
return _Uint8ListConversionSink(sink);
}
}
class _Uint8ListConversionSink implements Sink<List<int>> {
const _Uint8ListConversionSink(this._target);
final Sink<Uint8List> _target;
void add(List<int> data) {
_target.add(Uint8List.fromList(data));
}
void close() {
_target.close();
}
}
class _StreamSinkImpl<T> implements StreamSink<T> {
final StreamConsumer<T> _target;
final _doneCompleter = Completer<void>();
StreamController<T>? _controllerInstance;
Completer? _controllerCompleter;
bool _isClosed = false;
bool _isBound = false;
bool _hasError = false;
_StreamSinkImpl(this._target);
void add(T data) {
if (_isClosed) {
throw StateError("StreamSink is closed");
}
_controller.add(data);
}
void addError(Object error, [StackTrace? stackTrace]) {
if (_isClosed) {
throw StateError("StreamSink is closed");
}
_controller.addError(error, stackTrace);
}
Future addStream(Stream<T> stream) {
if (_isBound) {
throw StateError("StreamSink is already bound to a stream");
}
_isBound = true;
if (_hasError) return done;
// Wait for any sync operations to complete.
Future targetAddStream() {
return _target.addStream(stream).whenComplete(() {
_isBound = false;
});
}
var controller = _controllerInstance;
if (controller == null) return targetAddStream();
var future = _controllerCompleter!.future;
controller.close();
return future.then((_) => targetAddStream());
}
Future flush() {
if (_isBound) {
throw StateError("StreamSink is bound to a stream");
}
var controller = _controllerInstance;
if (controller == null) return Future.value(this);
// Adding an empty stream-controller will return a future that will complete
// when all data is done.
_isBound = true;
var future = _controllerCompleter!.future;
controller.close();
return future.whenComplete(() {
_isBound = false;
});
}
Future close() {
if (_isBound) {
throw StateError("StreamSink is bound to a stream");
}
if (!_isClosed) {
_isClosed = true;
var controller = _controllerInstance;
if (controller != null) {
controller.close();
} else {
_closeTarget();
}
}
return done;
}
void _closeTarget() {
_target.close().then(_completeDoneValue, onError: _completeDoneError);
}
Future get done => _doneCompleter.future;
void _completeDoneValue(value) {
if (!_doneCompleter.isCompleted) {
_doneCompleter.complete(value);
}
}
void _completeDoneError(Object error, StackTrace stackTrace) {
if (!_doneCompleter.isCompleted) {
_hasError = true;
_doneCompleter.completeError(error, stackTrace);
}
}
StreamController<T> get _controller {
if (_isBound) {
throw StateError("StreamSink is bound to a stream");
}
if (_isClosed) {
throw StateError("StreamSink is closed");