-
Notifications
You must be signed in to change notification settings - Fork 8
/
EmbraceUrlConnectionDelegate.java
929 lines (792 loc) · 31.2 KB
/
EmbraceUrlConnectionDelegate.java
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
package io.embrace.android.embracesdk.internal.network.http;
import static io.embrace.android.embracesdk.config.behavior.NetworkSpanForwardingBehavior.TRACEPARENT_HEADER_NAME;
import android.annotation.TargetApi;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.Permission;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocketFactory;
import io.embrace.android.embracesdk.Embrace;
import io.embrace.android.embracesdk.annotation.InternalApi;
import io.embrace.android.embracesdk.logging.InternalStaticEmbraceLogger;
import io.embrace.android.embracesdk.network.EmbraceNetworkRequest;
import io.embrace.android.embracesdk.network.http.HttpMethod;
import io.embrace.android.embracesdk.utils.exceptions.function.CheckedSupplier;
import kotlin.jvm.functions.Function0;
/**
* Wraps {@link HttpURLConnection} to log network calls to Embrace. The wrapper also wraps the
* InputStream to get an accurate count of bytes received if a Content-Length is not provided by
* the server.
* <p>
* The wrapper handles gzip decompression itself and strips the {@code Content-Length} and
* {@code Content-Encoding} headers. Typically this is handled transparently by
* {@link HttpURLConnection} but would prevent us from accessing the {@code Content-Length}.
* <p>
* Network logging currently does not follow redirects. The duration is logged from initiation of
* the network call (upon invocation of any method which would initiate the network call), to the
* retrieval of the response.
* <p>
* As network calls are initiated lazily, we log the network call prior to the calling of any
* wrapped method which would result in the network call actually being executed, and store a
* flag to prevent duplication of calls.
*/
@InternalApi
class EmbraceUrlConnectionDelegate<T extends HttpURLConnection> implements EmbraceHttpsUrlConnection {
/**
* The content encoding HTTP header.
*/
static final String CONTENT_ENCODING = "Content-Encoding";
/**
* The content length HTTP header.
*/
static final String CONTENT_LENGTH = "Content-Length";
/**
* Reference to the wrapped connection.
*/
private final T connection;
/**
* The time at which the connection was created.
*/
private final long createdTime;
/**
* Whether transparent gzip compression is enabled.
*/
private final boolean enableWrapIoStreams;
/**
* Reference to the SDK that is mockable and fakeable in tests
*/
private final Embrace embrace;
@NonNull
private final String callId;
/**
* A reference to the output stream wrapped in a counter, so we can determine the bytes sent.
*/
private volatile CountingOutputStream outputStream;
/**
* Whether the network call has already been logged, to prevent duplication.
*/
private volatile boolean didLogNetworkCall = false;
/**
* The time at which the network call ended.
*/
private volatile Long endTime;
/**
* The time at which the network call was initiated.
*/
private volatile Long startTime;
/**
* The trace id specified for the request
*/
private volatile String traceId;
/**
* The request headers captured from the http connection.
*/
private volatile HashMap<String, String> requestHeaders;
/**
* Indicates if the request throws a IOException
*/
private volatile Exception inputStreamAccessException;
private volatile Exception lastConnectionAccessException;
private final AtomicLong responseSize = new AtomicLong(-1);
private final AtomicInteger responseCode = new AtomicInteger(0);
private final AtomicReference<Map<String, List<String>>> headerFields = new AtomicReference<>(null);
private final AtomicReference<NetworkCaptureData> networkCaptureData = new AtomicReference<>(null);
@Nullable
private volatile String traceparent = null;
private final boolean isSDKStarted;
/**
* Wraps an existing {@link HttpURLConnection} with the Embrace network logic.
*
* @param connection the connection to wrap
* @param enableWrapIoStreams true if we should transparently ungzip the response, else false
*/
public EmbraceUrlConnectionDelegate(@NonNull T connection, boolean enableWrapIoStreams) {
this(connection, enableWrapIoStreams, Embrace.getInstance());
}
EmbraceUrlConnectionDelegate(@NonNull T connection, boolean enableWrapIoStreams,
@NonNull Embrace embrace) {
this.connection = connection;
this.enableWrapIoStreams = enableWrapIoStreams;
this.embrace = embrace;
this.createdTime = embrace.getInternalInterface().getSdkCurrentTime();
this.callId = UUID.randomUUID().toString();
this.isSDKStarted = embrace.isStarted();
}
@Override
public void addRequestProperty(@NonNull String key, @Nullable String value) {
this.connection.addRequestProperty(key, value);
}
@Override
public void connect() throws IOException {
if (isSDKStarted) {
identifyTraceId();
try {
if (embrace.getInternalInterface().isNetworkSpanForwardingEnabled()) {
traceparent = connection.getRequestProperty(TRACEPARENT_HEADER_NAME);
}
} catch (Exception e) {
// Ignore traceparent if there was a problem obtaining it
}
}
this.connection.connect();
}
@Override
public void disconnect() {
// The network call must be logged before we close the transport
internalLogNetworkCall(createdTime);
this.connection.disconnect();
}
@Override
public boolean getAllowUserInteraction() {
return this.connection.getAllowUserInteraction();
}
@Override
public void setAllowUserInteraction(boolean allowUserInteraction) {
this.connection.setAllowUserInteraction(allowUserInteraction);
}
@Override
public int getConnectTimeout() {
return this.connection.getConnectTimeout();
}
@Override
public void setConnectTimeout(int timeout) {
this.connection.setConnectTimeout(timeout);
}
@Override
@Nullable
public Object getContent() throws IOException {
identifyTraceId();
return this.connection.getContent();
}
@Override
@Nullable
public Object getContent(@NonNull Class<?>[] classes) throws IOException {
identifyTraceId();
return this.connection.getContent(classes);
}
@Override
@Nullable
public String getContentEncoding() {
return shouldUncompressGzip() ? null : this.connection.getContentEncoding();
}
@Override
public int getContentLength() {
return shouldUncompressGzip() ? -1 : this.connection.getContentLength();
}
@Override
@TargetApi(24)
public long getContentLengthLong() {
return (shouldUncompressGzip() || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) ?
-1 : this.connection.getContentLengthLong();
}
@Override
@Nullable
public String getContentType() {
return this.connection.getContentType();
}
@Override
public long getDate() {
return this.connection.getDate();
}
@Override
public boolean getDefaultUseCaches() {
return this.connection.getDefaultUseCaches();
}
@Override
public void setDefaultUseCaches(boolean defaultUseCaches) {
this.connection.setDefaultUseCaches(defaultUseCaches);
}
@Override
public boolean getDoInput() {
return this.connection.getDoInput();
}
@Override
public void setDoInput(boolean doInput) {
this.connection.setDoInput(doInput);
}
@Override
public boolean getDoOutput() {
return this.connection.getDoOutput();
}
@Override
public void setDoOutput(boolean doOutput) {
this.connection.setDoOutput(doOutput);
}
@Override
@Nullable
public InputStream getErrorStream() {
return getWrappedInputStream(this.connection.getErrorStream());
}
private boolean shouldInterceptHeaderRetrieval(@Nullable String key) {
return shouldUncompressGzip() && key != null && (key.equalsIgnoreCase(CONTENT_ENCODING) || key.equalsIgnoreCase(CONTENT_LENGTH));
}
@Override
@Nullable
public String getHeaderField(int n) {
String key = this.connection.getHeaderFieldKey(n);
return retrieveHeaderField(key,
null,
() -> connection.getHeaderField(n)
);
}
@Override
@Nullable
public String getHeaderField(@Nullable String name) {
return retrieveHeaderField(name,
null,
() -> connection.getHeaderField(name)
);
}
@Override
@Nullable
public String getHeaderFieldKey(int n) {
String key = this.connection.getHeaderFieldKey(n);
return retrieveHeaderField(key,
null,
() -> key
);
}
@Override
public long getHeaderFieldDate(@NonNull String name, long defaultValue) {
Long result = retrieveHeaderField(name,
defaultValue,
() -> connection.getHeaderFieldDate(name, defaultValue)
);
return result != null ? result : defaultValue;
}
@Override
public int getHeaderFieldInt(@NonNull String name, int defaultValue) {
Integer result = retrieveHeaderField(name,
defaultValue,
() -> connection.getHeaderFieldInt(name, defaultValue)
);
return result != null ? result : defaultValue;
}
@Override
@TargetApi(24)
public long getHeaderFieldLong(@NonNull String name, long defaultValue) {
Long result = retrieveHeaderField(name,
defaultValue,
() -> Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? -1 :
this.connection.getHeaderFieldLong(name, defaultValue)
);
return result != null ? result : defaultValue;
}
@Override
@Nullable
public Map<String, List<String>> getHeaderFields() {
final long startTime = embrace.getInternalInterface().getSdkCurrentTime();
cacheNetworkCallData();
internalLogNetworkCall(startTime);
return headerFields.get();
}
private <R> R retrieveHeaderField(@Nullable String name,
R defaultValue,
Function0<R> action) {
if (name == null) {
return null;
}
long startTime = embrace.getInternalInterface().getSdkCurrentTime();
if (shouldInterceptHeaderRetrieval(name)) {
// Strip the content encoding and length headers, as we transparently ungzip the content
return defaultValue;
}
R result = action.invoke();
cacheNetworkCallData();
internalLogNetworkCall(startTime);
return result;
}
@Override
public long getIfModifiedSince() {
return this.connection.getIfModifiedSince();
}
@Override
public void setIfModifiedSince(long ifModifiedSince) {
this.connection.setIfModifiedSince(ifModifiedSince);
}
@Override
@Nullable
public InputStream getInputStream() throws IOException {
try {
return getWrappedInputStream(this.connection.getInputStream());
} catch (IOException e) {
inputStreamAccessException = e;
throw e;
}
}
@Override
public boolean getInstanceFollowRedirects() {
return this.connection.getInstanceFollowRedirects();
}
@Override
public void setInstanceFollowRedirects(boolean followRedirects) {
this.connection.setInstanceFollowRedirects(followRedirects);
}
@Override
public long getLastModified() {
return this.connection.getLastModified();
}
@Override
@Nullable
public OutputStream getOutputStream() throws IOException {
identifyTraceId();
OutputStream out = connection.getOutputStream();
if (enableWrapIoStreams && this.outputStream == null && out != null) {
this.outputStream = new CountingOutputStream(out);
return this.outputStream;
}
return out;
}
@Override
@Nullable
public Permission getPermission() throws IOException {
return this.connection.getPermission();
}
@Override
public int getReadTimeout() {
return this.connection.getReadTimeout();
}
@Override
public void setReadTimeout(int timeout) {
this.connection.setReadTimeout(timeout);
}
@Override
@NonNull
public String getRequestMethod() {
return this.connection.getRequestMethod();
}
@Override
public void setRequestMethod(@NonNull String method) throws ProtocolException {
this.connection.setRequestMethod(method);
}
@Override
@Nullable
public Map<String, List<String>> getRequestProperties() {
return this.connection.getRequestProperties();
}
@Override
@Nullable
public String getRequestProperty(@NonNull String key) {
return this.connection.getRequestProperty(key);
}
@Override
public int getResponseCode() {
identifyTraceId();
long startTime = embrace.getInternalInterface().getSdkCurrentTime();
cacheNetworkCallData();
internalLogNetworkCall(startTime);
return responseCode.get();
}
@Override
@Nullable
public String getResponseMessage() throws IOException {
identifyTraceId();
long startTime = embrace.getInternalInterface().getSdkCurrentTime();
String responseMsg = this.connection.getResponseMessage();
cacheNetworkCallData();
internalLogNetworkCall(startTime);
return responseMsg;
}
@Override
@Nullable
public URL getUrl() {
return this.connection.getURL();
}
@Override
public boolean getUseCaches() {
return this.connection.getUseCaches();
}
@Override
public void setUseCaches(boolean useCaches) {
this.connection.setUseCaches(useCaches);
}
@Override
public void setChunkedStreamingMode(int chunkLen) {
this.connection.setChunkedStreamingMode(chunkLen);
}
@Override
public void setFixedLengthStreamingMode(int contentLength) {
this.connection.setFixedLengthStreamingMode(contentLength);
}
@Override
public void setFixedLengthStreamingMode(long contentLength) {
this.connection.setFixedLengthStreamingMode(contentLength);
}
@Override
public void setRequestProperty(@NonNull String key, @Nullable String value) {
this.connection.setRequestProperty(key, value);
if (hasNetworkCaptureRules()) {
this.requestHeaders = getProcessedHeaders(getRequestProperties());
}
}
@Override
@NonNull
public String toString() {
return this.connection.toString();
}
@Override
public boolean usingProxy() {
return this.connection.usingProxy();
}
/**
* Given a start time (in milliseconds), logs the network call to Embrace using the current time as the end time.
* <p>
* If the network call has already been logged for this HttpURLConnection, this method is a no-op and is effectively
* ignored.
*/
synchronized void internalLogNetworkCall(long startTime) {
if (isSDKStarted) {
internalLogNetworkCall(startTime, embrace.getInternalInterface().getSdkCurrentTime(), false);
}
}
/**
* Given a start time and end time (in milliseconds), logs the network call to Embrace.
* <p>
* If this delegate has already logged the call it represents, this method is a no-op unless "overwrite" is true, in which
* case it will overwrite the previously logged call with new data (basically the network capture information if it's turned on)
*/
synchronized void internalLogNetworkCall(long startTime, long endTime, boolean overwrite) {
if (!this.didLogNetworkCall || overwrite) {
// We are proactive with setting this flag so that we don't get nested calls to log the network call by virtue of
// extracting the data we need to log the network call.
this.didLogNetworkCall = true;
this.startTime = startTime;
this.endTime = endTime;
String url = EmbraceHttpPathOverride.getURLString(new EmbraceHttpUrlConnectionOverride(this.connection));
try {
long bytesOut = this.outputStream == null ? 0 : Math.max(this.outputStream.getCount(), 0);
long contentLength = Math.max(0, responseSize.get());
if (inputStreamAccessException == null && lastConnectionAccessException == null && responseCode.get() != 0) {
embrace.getInternalInterface().recordAndDeduplicateNetworkRequest(
callId,
EmbraceNetworkRequest.fromCompletedRequest(
url,
HttpMethod.fromString(getRequestMethod()),
startTime,
endTime,
bytesOut,
contentLength,
responseCode.get(),
traceId,
traceparent,
networkCaptureData.get()
)
);
} else {
String exceptionClass = null;
String exceptionMessage = null;
// Error that happened when trying to obtain the input stream take precedent over connection access errors after that
if (inputStreamAccessException != null) {
exceptionClass = inputStreamAccessException.getClass().getCanonicalName();
exceptionMessage = inputStreamAccessException.getMessage();
} else if (lastConnectionAccessException != null) {
exceptionClass = lastConnectionAccessException.getClass().getCanonicalName();
exceptionMessage = lastConnectionAccessException.getMessage();
}
String errorType = exceptionClass != null ? exceptionClass : "UnknownState";
String errorMessage = exceptionMessage != null ? exceptionMessage : "HTTP response state unknown";
embrace.getInternalInterface().recordAndDeduplicateNetworkRequest(
callId,
EmbraceNetworkRequest.fromIncompleteRequest(
url,
HttpMethod.fromString(getRequestMethod()),
startTime,
endTime,
errorType,
errorMessage,
traceId,
traceparent,
networkCaptureData.get()
)
);
}
} catch (Exception e) {
InternalStaticEmbraceLogger.logError("Error logging native network request", e);
}
}
}
@Nullable
private HashMap<String, String> getProcessedHeaders(@Nullable Map<String, List<String>> properties) {
if (properties == null) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
for (Map.Entry<String, List<String>> h : properties.entrySet()) {
StringBuilder builder = new StringBuilder();
for (String value : h.getValue()) {
if (value != null) {
builder.append(value);
}
}
headers.put(h.getKey(), builder.toString());
}
return headers;
}
/**
* Wraps an input stream with an input stream which counts the number of bytes read, and then
* updates the network call service with the correct number of bytes read once the stream has
* reached the end.
*
* @param inputStream the input stream to count
* @return the wrapped input stream
*/
private CountingInputStreamWithCallback countingInputStream(InputStream inputStream) {
return new CountingInputStreamWithCallback(
inputStream,
hasNetworkCaptureRules(),
(bytesCount, responseBody) -> {
if (startTime != null && endTime != null) {
cacheNetworkCallData(responseBody);
internalLogNetworkCall(startTime, endTime,true);
}
});
}
/**
* We disable the automatic gzip decompression behavior of {@link HttpURLConnection} in the
* {@link EmbraceHttpUrlStreamHandler} to ensure that we can count the bytes in the response
* from the server. We decompress the response transparently to the user only if both:
* <ul>
* <li>The user did not specify an encoding</li>
* <li>The server returned a gzipped response</li>
* </ul>
* <p>
* If the user specified an encoding, even if it is gzip, we do not transparently decompress
* the response. This is to mirror the behavior of {@link HttpURLConnection} whilst providing
* us access to the content length.
*
* @return true if we should decompress the response, false otherwise
* @see <a href="https://developer.android.com/reference/java/net/HttpURLConnection#performance">Android Docs</a>
* @see <a href="https://android.googlesource.com/platform/external/okhttp/+/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java">Android Source Code</a>
*/
private boolean shouldUncompressGzip() {
String contentEncoding = this.connection.getContentEncoding();
return enableWrapIoStreams &&
contentEncoding != null &&
contentEncoding.equalsIgnoreCase("gzip");
}
private void identifyTraceId() {
if (isSDKStarted && traceId == null) {
try {
traceId = getRequestProperty(embrace.getTraceIdHeader());
} catch (Exception e) {
InternalStaticEmbraceLogger.logDebug("Failed to retrieve actual trace id header. Current: " + traceId);
}
}
}
@Override
@Nullable
public String getCipherSuite() {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getCipherSuite();
}
return null;
}
@Override
@Nullable
public Certificate[] getLocalCertificates() {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getLocalCertificates();
}
return new Certificate[0];
}
@Override
@Nullable
public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getServerCertificates();
}
return new Certificate[0];
}
@Override
@Nullable
public SSLSocketFactory getSslSocketFactory() {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getSSLSocketFactory();
}
return null;
}
@Override
public void setSslSocketFactory(@NonNull SSLSocketFactory factory) {
if (this.connection instanceof HttpsURLConnection) {
((HttpsURLConnection) this.connection).setSSLSocketFactory(factory);
}
}
@Override
@Nullable
public HostnameVerifier getHostnameVerifier() {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getHostnameVerifier();
}
return null;
}
@Override
public void setHostnameVerifier(@NonNull HostnameVerifier verifier) {
if (this.connection instanceof HttpsURLConnection) {
((HttpsURLConnection) this.connection).setHostnameVerifier(verifier);
}
}
@Override
@Nullable
public Principal getLocalPrincipal() {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getLocalPrincipal();
}
return null;
}
@Override
@Nullable
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
if (this.connection instanceof HttpsURLConnection) {
return ((HttpsURLConnection) this.connection).getPeerPrincipal();
}
return null;
}
@Nullable
private InputStream getWrappedInputStream(InputStream connectionInputStream) {
identifyTraceId();
long startTime = embrace.getInternalInterface().getSdkCurrentTime();
InputStream in = null;
if (shouldUncompressGzip()) {
try {
CheckedSupplier<GZIPInputStream> gzipInputStreamSupplier = () -> new GZIPInputStream(connectionInputStream);
in = countingInputStream(new BufferedInputStream(gzipInputStreamSupplier.get()));
} catch (Throwable t) {
// This handles the case where it's availability is 0, causing the GZIPInputStream instantiation to fail.
}
}
if (in == null) {
in = enableWrapIoStreams ?
countingInputStream(new BufferedInputStream(connectionInputStream)) : connectionInputStream;
}
cacheNetworkCallData();
internalLogNetworkCall(startTime);
return in;
}
private boolean hasNetworkCaptureRules() {
if (!isSDKStarted || this.connection.getURL() == null) {
return false;
}
String url = this.connection.getURL().toString();
String method = this.connection.getRequestMethod();
return embrace.getInternalInterface().shouldCaptureNetworkBody(url, method);
}
private void cacheNetworkCallData() {
if (isSDKStarted) {
cacheNetworkCallData(null);
}
}
/**
* Cache values from response at the first point of availability so that we won't try to retrieve these values when the response
* is not available.
*/
private void cacheNetworkCallData(@Nullable byte[] responseBody) {
if (headerFields.get() == null) {
synchronized (headerFields) {
if (headerFields.get() == null) {
try {
final Map<String, List<String>> responseHeaders;
if (!enableWrapIoStreams) {
responseHeaders = connection.getHeaderFields();
} else {
responseHeaders = new HashMap<>(connection.getHeaderFields());
responseHeaders.remove(CONTENT_ENCODING);
responseHeaders.remove(CONTENT_LENGTH);
}
headerFields.set(responseHeaders);
} catch (Exception e) {
lastConnectionAccessException = e;
}
}
}
}
if (responseCode.get() == 0) {
synchronized (responseCode) {
if (responseCode.get() == 0) {
try {
responseCode.set(connection.getResponseCode());
} catch (Exception e) {
lastConnectionAccessException = e;
}
}
}
}
if (responseSize.get() == -1) {
synchronized (responseSize) {
// Only try to retrieve the response size if the connection is connected.
// Doing so when the connection is finished and has disconnected will result in the re-execution of the request
if (responseSize.get() == -1) {
try {
responseSize.set(connection.getContentLength());
} catch (Exception e) {
lastConnectionAccessException = e;
}
}
}
}
if (shouldCaptureNetworkData()) {
// If we don't have network capture rules, it's unnecessary to save these values
synchronized (networkCaptureData) {
if (shouldCaptureNetworkData()) {
try {
NetworkCaptureData existingData = networkCaptureData.get();
if (existingData == null) {
Map<String, String> requestHeaders = this.requestHeaders;
String requestQueryParams = connection.getURL().getQuery();
byte[] requestBody = this.outputStream != null ? this.outputStream.getRequestBody() : null;
Map<String, String> responseHeaders = getProcessedHeaders(headerFields.get());
networkCaptureData.set(
new NetworkCaptureData(
requestHeaders,
requestQueryParams,
requestBody,
responseHeaders,
responseBody,
null
)
);
} else if (responseBody != null) {
// Update the response body field in the cached networkCaptureData object if a subsequent call
// is update to update the network logging with this data.
networkCaptureData.set(
new NetworkCaptureData(
existingData.getRequestHeaders(),
existingData.getRequestQueryParams(),
existingData.getCapturedRequestBody(),
existingData.getResponseHeaders(),
responseBody,
null
)
);
}
} catch (Exception e) {
lastConnectionAccessException = e;
}
}
}
}
}
private boolean shouldCaptureNetworkData() {
return (hasNetworkCaptureRules() && (enableWrapIoStreams || inputStreamAccessException != null)) &&
(networkCaptureData.get() == null || networkCaptureData.get().getCapturedResponseBody() == null);
}
}