summaryrefslogtreecommitdiff
path: root/service/src/com/android/server/connectivity/QosCallbackTracker.java
blob: b6ab47b276e330382aba8210f74ef10d0562582c (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
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
/*
 * Copyright (C) 2020 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.server.connectivity;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.net.IQosCallback;
import android.net.Network;
import android.net.QosCallbackException;
import android.net.QosFilter;
import android.net.QosSession;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.data.EpsBearerQosSessionAttributes;
import android.telephony.data.NrQosSessionAttributes;
import android.util.Log;

import com.android.net.module.util.CollectionUtils;
import com.android.server.ConnectivityService;

import java.util.ArrayList;
import java.util.List;

/**
 * Tracks qos callbacks and handles the communication between the network agent and application.
 * <p/>
 * Any method prefixed by handle must be called from the
 * {@link com.android.server.ConnectivityService} handler thread.
 *
 * @hide
 */
public class QosCallbackTracker {
    private static final String TAG = QosCallbackTracker.class.getSimpleName();
    private static final boolean DBG = true;

    @NonNull
    private final Handler mConnectivityServiceHandler;

    @NonNull
    private final ConnectivityService.PerUidCounter mNetworkRequestCounter;

    /**
     * Each agent gets a unique callback id that is used to proxy messages back to the original
     * callback.
     * <p/>
     * Note: The fact that this is initialized to 0 is to ensure that the thread running
     * {@link #handleRegisterCallback(IQosCallback, QosFilter, int, NetworkAgentInfo)} sees the
     * initialized value. This would not necessarily be the case if the value was initialized to
     * the non-default value.
     * <p/>
     * Note: The term previous does not apply to the first callback id that is assigned.
     */
    private int mPreviousAgentCallbackId = 0;

    @NonNull
    private final List<QosCallbackAgentConnection> mConnections = new ArrayList<>();

    /**
     *
     * @param connectivityServiceHandler must be the same handler used with
     *                {@link com.android.server.ConnectivityService}
     * @param networkRequestCounter keeps track of the number of open requests under a given
     *                              uid
     */
    public QosCallbackTracker(@NonNull final Handler connectivityServiceHandler,
            final ConnectivityService.PerUidCounter networkRequestCounter) {
        mConnectivityServiceHandler = connectivityServiceHandler;
        mNetworkRequestCounter = networkRequestCounter;
    }

    /**
     * Registers the callback with the tracker
     *
     * @param callback the callback to register
     * @param filter the filter being registered alongside the callback
     */
    public void registerCallback(@NonNull final IQosCallback callback,
            @NonNull final QosFilter filter, @NonNull final NetworkAgentInfo networkAgentInfo) {
        final int uid = Binder.getCallingUid();

        // Enforce that the number of requests under this uid has exceeded the allowed number
        mNetworkRequestCounter.incrementCountOrThrow(uid);

        mConnectivityServiceHandler.post(
                () -> handleRegisterCallback(callback, filter, uid, networkAgentInfo));
    }

    private void handleRegisterCallback(@NonNull final IQosCallback callback,
            @NonNull final QosFilter filter, final int uid,
            @NonNull final NetworkAgentInfo networkAgentInfo) {
        final QosCallbackAgentConnection ac =
                handleRegisterCallbackInternal(callback, filter, uid, networkAgentInfo);
        if (ac != null) {
            if (DBG) log("handleRegisterCallback: added callback " + ac.getAgentCallbackId());
            mConnections.add(ac);
        } else {
            mNetworkRequestCounter.decrementCount(uid);
        }
    }

    private QosCallbackAgentConnection handleRegisterCallbackInternal(
            @NonNull final IQosCallback callback,
            @NonNull final QosFilter filter, final int uid,
            @NonNull final NetworkAgentInfo networkAgentInfo) {
        final IBinder binder = callback.asBinder();
        if (CollectionUtils.any(mConnections, c -> c.getBinder().equals(binder))) {
            // A duplicate registration would have only made this far due to a programming error.
            logwtf("handleRegisterCallback: Callbacks can only be register once.");
            return null;
        }

        mPreviousAgentCallbackId = mPreviousAgentCallbackId + 1;
        final int newCallbackId = mPreviousAgentCallbackId;

        final QosCallbackAgentConnection ac =
                new QosCallbackAgentConnection(this, newCallbackId, callback,
                        filter, uid, networkAgentInfo);

        final int exceptionType = filter.validate();
        if (exceptionType != QosCallbackException.EX_TYPE_FILTER_NONE) {
            ac.sendEventQosCallbackError(exceptionType);
            return null;
        }

        // Only add to the callback maps if the NetworkAgent successfully registered it
        if (!ac.sendCmdRegisterCallback()) {
            // There was an issue when registering the agent
            if (DBG) log("handleRegisterCallback: error sending register callback");
            mNetworkRequestCounter.decrementCount(uid);
            return null;
        }
        return ac;
    }

    /**
     * Unregisters callback
     * @param callback callback to unregister
     */
    public void unregisterCallback(@NonNull final IQosCallback callback) {
        mConnectivityServiceHandler.post(() -> handleUnregisterCallback(callback.asBinder(), true));
    }

    private void handleUnregisterCallback(@NonNull final IBinder binder,
            final boolean sendToNetworkAgent) {
        final int connIndex =
                CollectionUtils.indexOf(mConnections, c -> c.getBinder().equals(binder));
        if (connIndex < 0) {
            logw("handleUnregisterCallback: no matching agentConnection");
            return;
        }
        final QosCallbackAgentConnection agentConnection = mConnections.get(connIndex);

        if (DBG) {
            log("handleUnregisterCallback: unregister "
                    + agentConnection.getAgentCallbackId());
        }

        mNetworkRequestCounter.decrementCount(agentConnection.getUid());
        mConnections.remove(agentConnection);

        if (sendToNetworkAgent) {
            agentConnection.sendCmdUnregisterCallback();
        }
        agentConnection.unlinkToDeathRecipient();
    }

    /**
     * Called when the NetworkAgent sends the qos session available event for EPS
     *
     * @param qosCallbackId the callback id that the qos session is now available to
     * @param session the qos session that is now available
     * @param attributes the qos attributes that are now available on the qos session
     */
    public void sendEventEpsQosSessionAvailable(final int qosCallbackId,
            final QosSession session,
            final EpsBearerQosSessionAttributes attributes) {
        runOnAgentConnection(qosCallbackId, "sendEventEpsQosSessionAvailable: ",
                ac -> ac.sendEventEpsQosSessionAvailable(session, attributes));
    }

    /**
     * Called when the NetworkAgent sends the qos session available event for NR
     *
     * @param qosCallbackId the callback id that the qos session is now available to
     * @param session the qos session that is now available
     * @param attributes the qos attributes that are now available on the qos session
     */
    public void sendEventNrQosSessionAvailable(final int qosCallbackId,
            final QosSession session,
            final NrQosSessionAttributes attributes) {
        runOnAgentConnection(qosCallbackId, "sendEventNrQosSessionAvailable: ",
                ac -> ac.sendEventNrQosSessionAvailable(session, attributes));
    }

    /**
     * Called when the NetworkAgent sends the qos session lost event
     *
     * @param qosCallbackId the callback id that lost the qos session
     * @param session the corresponding qos session
     */
    public void sendEventQosSessionLost(final int qosCallbackId,
            final QosSession session) {
        runOnAgentConnection(qosCallbackId, "sendEventQosSessionLost: ",
                ac -> ac.sendEventQosSessionLost(session));
    }

    /**
     * Called when the NetworkAgent sends the qos session on error event
     *
     * @param qosCallbackId the callback id that should receive the exception
     * @param exceptionType the type of exception that caused the callback to error
     */
    public void sendEventQosCallbackError(final int qosCallbackId,
            @QosCallbackException.ExceptionType final int exceptionType) {
        runOnAgentConnection(qosCallbackId, "sendEventQosCallbackError: ",
                ac -> {
                    ac.sendEventQosCallbackError(exceptionType);
                    handleUnregisterCallback(ac.getBinder(), false);
                });
    }

    /**
     * Unregisters all callbacks associated to this network agent
     *
     * Note: Must be called on the connectivity service handler thread
     *
     * @param network the network that was released
     */
    public void handleNetworkReleased(@Nullable final Network network) {
        // Iterate in reverse order as agent connections will be removed when unregistering
        for (int i = mConnections.size() - 1; i >= 0; i--) {
            final QosCallbackAgentConnection agentConnection = mConnections.get(i);
            if (!agentConnection.getNetwork().equals(network)) continue;
            agentConnection.sendEventQosCallbackError(
                    QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);

            // Call unregister workflow w\o sending anything to agent since it is disconnected.
            handleUnregisterCallback(agentConnection.getBinder(), false);
        }
    }

    private interface AgentConnectionAction {
        void execute(@NonNull QosCallbackAgentConnection agentConnection);
    }

    @Nullable
    private void runOnAgentConnection(final int qosCallbackId,
            @NonNull final String logPrefix,
            @NonNull final AgentConnectionAction action) {
        mConnectivityServiceHandler.post(() -> {
            final int acIndex = CollectionUtils.indexOf(mConnections,
                            c -> c.getAgentCallbackId() == qosCallbackId);
            if (acIndex == -1) {
                loge(logPrefix + ": " + qosCallbackId + " missing callback id");
                return;
            }

            action.execute(mConnections.get(acIndex));
        });
    }

    private static void log(final String msg) {
        Log.d(TAG, msg);
    }

    private static void logw(final String msg) {
        Log.w(TAG, msg);
    }

    private static void loge(final String msg) {
        Log.e(TAG, msg);
    }

    private static void logwtf(final String msg) {
        Log.wtf(TAG, msg);
    }
}