summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/service/measurement/MeasurementHttpClient.java
blob: 8f05c536d604da1b580a3f85139d904ec84d9437 (plain)
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
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.adservices.service.measurement;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.adservices.LogUtil;
import com.android.adservices.service.Flags;
import com.android.adservices.service.FlagsFactory;

import com.google.common.base.Charsets;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * Utility class related to network related activities
 *
 * @hide
 */
public class MeasurementHttpClient {

    enum HttpMethod {
        GET,
        POST
    }

    /**
     * Opens a {@link URLConnection} and sets the network connection & read timeout. The timeout
     * values are configurable using the name "measurement_network_connect_timeout_ms" and
     * "measurement_network_read_timeout_ms"
     */
    @NonNull
    public URLConnection setup(@NonNull URL url) throws IOException {
        Objects.requireNonNull(url);

        final URLConnection urlConnection = url.openConnection();
        final Flags flags = FlagsFactory.getFlags();
        urlConnection.setConnectTimeout(flags.getMeasurementNetworkConnectTimeoutMs());
        urlConnection.setReadTimeout(flags.getMeasurementNetworkReadTimeoutMs());

        // Overriding default headers to avoid leaking information
        urlConnection.setRequestProperty("User-Agent", "");

        return urlConnection;
    }

    /**
     * Rest call execution, if an error is encountered before performing the network call or an
     * {@link IOException} is thrown, an empty {@link Optional} will be returned.
     */
    @NonNull
    public Optional<MeasurementHttpResponse> call(
            @NonNull String endpoint,
            @NonNull HttpMethod httpMethod,
            @Nullable Map<String, String> headers,
            @Nullable JSONObject payload,
            boolean followRedirects) {
        if (endpoint == null || httpMethod == null) {
            LogUtil.d("Endpoint or http method is empty");
            return Optional.empty();
        }

        final URL url;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            LogUtil.e(e, "Malformed registration target URL");
            return Optional.empty();
        }

        final HttpURLConnection urlConnection;
        try {
            urlConnection = (HttpURLConnection) setup(url);
        } catch (IOException e) {
            LogUtil.e(e, "Failed to open target URL");
            return Optional.empty();
        }

        try {

            urlConnection.setRequestMethod(httpMethod.name());

            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (payload != null) {
                urlConnection.setDoOutput(true);
                try (BufferedOutputStream out =
                        new BufferedOutputStream(urlConnection.getOutputStream())) {
                    out.write(payload.toString().getBytes());
                    out.flush();
                }
            }

            urlConnection.setInstanceFollowRedirects(followRedirects);

            int responseCode = urlConnection.getResponseCode();
            if (responseCode / 100 == 2) {
                return Optional.of(
                        new MeasurementHttpResponse.Builder()
                                .setPayload(convert(urlConnection.getInputStream()))
                                .setHeaders(urlConnection.getHeaderFields())
                                .setStatusCode(responseCode)
                                .build());
            } else {
                return Optional.of(
                        new MeasurementHttpResponse.Builder()
                                .setPayload(convert(urlConnection.getErrorStream()))
                                .setHeaders(urlConnection.getHeaderFields())
                                .setStatusCode(responseCode)
                                .build());
            }
        } catch (IOException e) {
            LogUtil.e(e, "Failed to get registration response");
            return Optional.empty();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    private String convert(@NonNull InputStream in) throws IOException {
        if (in == null) {
            return null;
        }
        return new String(in.readAllBytes(), Charsets.UTF_8);
    }
}