liyujie
2025-08-28 b3810562527858a3b3d98ffa6e9c9c5b0f4a9a8e
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
/*
 * Copyright (C) 2014 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 android.net;
 
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.util.SparseArray;
 
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Protocol;
 
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * A NetworkFactory is an entity that creates NetworkAgent objects.
 * The bearers register with ConnectivityService using {@link #register} and
 * their factory will start receiving scored NetworkRequests.  NetworkRequests
 * can be filtered 3 ways: by NetworkCapabilities, by score and more complexly by
 * overridden function.  All of these can be dynamic - changing NetworkCapabilities
 * or score forces re-evaluation of all current requests.
 *
 * If any requests pass the filter some overrideable functions will be called.
 * If the bearer only cares about very simple start/stopNetwork callbacks, those
 * functions can be overridden.  If the bearer needs more interaction, it can
 * override addNetworkRequest and removeNetworkRequest which will give it each
 * request that passes their current filters.
 * @hide
 **/
public class NetworkFactory extends Handler {
    /** @hide */
    public static class SerialNumber {
        // Guard used by no network factory.
        public static final int NONE = -1;
        // A hardcoded serial number for NetworkAgents representing VPNs. These agents are
        // not created by any factory, so they use this constant for clarity instead of NONE.
        public static final int VPN = -2;
        private static final AtomicInteger sNetworkFactorySerialNumber = new AtomicInteger(1);
        /** Returns a unique serial number for a factory. */
        public static final int nextSerialNumber() {
            return sNetworkFactorySerialNumber.getAndIncrement();
        }
    }
 
    private static final boolean DBG = true;
    private static final boolean VDBG = false;
 
    private static final int BASE = Protocol.BASE_NETWORK_FACTORY;
    /**
     * Pass a network request to the bearer.  If the bearer believes it can
     * satisfy the request it should connect to the network and create a
     * NetworkAgent.  Once the NetworkAgent is fully functional it will
     * register itself with ConnectivityService using registerNetworkAgent.
     * If the bearer cannot immediately satisfy the request (no network,
     * user disabled the radio, lower-scored network) it should remember
     * any NetworkRequests it may be able to satisfy in the future.  It may
     * disregard any that it will never be able to service, for example
     * those requiring a different bearer.
     * msg.obj = NetworkRequest
     * msg.arg1 = score - the score of the network currently satisfying this
     *            request.  If this bearer knows in advance it cannot
     *            exceed this score it should not try to connect, holding the request
     *            for the future.
     *            Note that subsequent events may give a different (lower
     *            or higher) score for this request, transmitted to each
     *            NetworkFactory through additional CMD_REQUEST_NETWORK msgs
     *            with the same NetworkRequest but an updated score.
     *            Also, network conditions may change for this bearer
     *            allowing for a better score in the future.
     * msg.arg2 = the serial number of the factory currently responsible for the
     *            NetworkAgent handling this request, or SerialNumber.NONE if none.
     */
    public static final int CMD_REQUEST_NETWORK = BASE;
 
    /**
     * Cancel a network request
     * msg.obj = NetworkRequest
     */
    public static final int CMD_CANCEL_REQUEST = BASE + 1;
 
    /**
     * Internally used to set our best-guess score.
     * msg.arg1 = new score
     */
    private static final int CMD_SET_SCORE = BASE + 2;
 
    /**
     * Internally used to set our current filter for coarse bandwidth changes with
     * technology changes.
     * msg.obj = new filter
     */
    private static final int CMD_SET_FILTER = BASE + 3;
 
    /**
     * Sent by NetworkFactory to ConnectivityService to indicate that a request is
     * unfulfillable.
     * @see #releaseRequestAsUnfulfillableByAnyFactory(NetworkRequest).
     */
    public static final int EVENT_UNFULFILLABLE_REQUEST = BASE + 4;
 
    private final Context mContext;
    private final ArrayList<Message> mPreConnectedQueue = new ArrayList<Message>();
    private AsyncChannel mAsyncChannel;
    private final String LOG_TAG;
 
    private final SparseArray<NetworkRequestInfo> mNetworkRequests =
            new SparseArray<NetworkRequestInfo>();
 
    private int mScore;
    private NetworkCapabilities mCapabilityFilter;
 
    private int mRefCount = 0;
    private Messenger mMessenger = null;
    private int mSerialNumber;
 
    @UnsupportedAppUsage
    public NetworkFactory(Looper looper, Context context, String logTag,
            NetworkCapabilities filter) {
        super(looper);
        LOG_TAG = logTag;
        mContext = context;
        mCapabilityFilter = filter;
    }
 
    public void register() {
        if (DBG) log("Registering NetworkFactory");
        if (mMessenger == null) {
            mMessenger = new Messenger(this);
            mSerialNumber = ConnectivityManager.from(mContext).registerNetworkFactory(mMessenger,
                    LOG_TAG);
        }
    }
 
    public void unregister() {
        if (DBG) log("Unregistering NetworkFactory");
        if (mMessenger != null) {
            ConnectivityManager.from(mContext).unregisterNetworkFactory(mMessenger);
            mMessenger = null;
        }
    }
 
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
                if (mAsyncChannel != null) {
                    log("Received new connection while already connected!");
                    break;
                }
                if (VDBG) log("NetworkFactory fully connected");
                AsyncChannel ac = new AsyncChannel();
                ac.connected(null, this, msg.replyTo);
                ac.replyToMessage(msg, AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED,
                        AsyncChannel.STATUS_SUCCESSFUL);
                mAsyncChannel = ac;
                for (Message m : mPreConnectedQueue) {
                    ac.sendMessage(m);
                }
                mPreConnectedQueue.clear();
                break;
            }
            case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
                if (VDBG) log("CMD_CHANNEL_DISCONNECT");
                if (mAsyncChannel != null) {
                    mAsyncChannel.disconnect();
                    mAsyncChannel = null;
                }
                break;
            }
            case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
                if (DBG) log("NetworkFactory channel lost");
                mAsyncChannel = null;
                break;
            }
            case CMD_REQUEST_NETWORK: {
                handleAddRequest((NetworkRequest) msg.obj, msg.arg1, msg.arg2);
                break;
            }
            case CMD_CANCEL_REQUEST: {
                handleRemoveRequest((NetworkRequest) msg.obj);
                break;
            }
            case CMD_SET_SCORE: {
                handleSetScore(msg.arg1);
                break;
            }
            case CMD_SET_FILTER: {
                handleSetFilter((NetworkCapabilities) msg.obj);
                break;
            }
        }
    }
 
    private class NetworkRequestInfo {
        public final NetworkRequest request;
        public int score;
        public boolean requested; // do we have a request outstanding, limited by score
        public int factorySerialNumber;
 
        NetworkRequestInfo(NetworkRequest request, int score, int factorySerialNumber) {
            this.request = request;
            this.score = score;
            this.requested = false;
            this.factorySerialNumber = factorySerialNumber;
        }
 
        @Override
        public String toString() {
            return "{" + request + ", score=" + score + ", requested=" + requested + "}";
        }
    }
 
    /**
     * Add a NetworkRequest that the bearer may want to attempt to satisfy.
     * @see #CMD_REQUEST_NETWORK
     *
     * @param request the request to handle.
     * @param score the score of the NetworkAgent currently satisfying this request.
     * @param servingFactorySerialNumber the serial number of the NetworkFactory that
     *         created the NetworkAgent currently satisfying this request.
     */
    // TODO : remove this method. It is a stopgap measure to help sheperding a number
    // of dependent changes that would conflict throughout the automerger graph. Having this
    // temporarily helps with the process of going through with all these dependent changes across
    // the entire tree.
    @VisibleForTesting
    protected void handleAddRequest(NetworkRequest request, int score) {
        handleAddRequest(request, score, SerialNumber.NONE);
    }
 
    /**
     * Add a NetworkRequest that the bearer may want to attempt to satisfy.
     * @see #CMD_REQUEST_NETWORK
     *
     * @param request the request to handle.
     * @param score the score of the NetworkAgent currently satisfying this request.
     * @param servingFactorySerialNumber the serial number of the NetworkFactory that
     *         created the NetworkAgent currently satisfying this request.
     */
    @VisibleForTesting
    protected void handleAddRequest(NetworkRequest request, int score,
            int servingFactorySerialNumber) {
        NetworkRequestInfo n = mNetworkRequests.get(request.requestId);
        if (n == null) {
            if (DBG) {
                log("got request " + request + " with score " + score
                        + " and serial " + servingFactorySerialNumber);
            }
            n = new NetworkRequestInfo(request, score, servingFactorySerialNumber);
            mNetworkRequests.put(n.request.requestId, n);
        } else {
            if (VDBG) {
                log("new score " + score + " for exisiting request " + request
                        + " with serial " + servingFactorySerialNumber);
            }
            n.score = score;
            n.factorySerialNumber = servingFactorySerialNumber;
        }
        if (VDBG) log("  my score=" + mScore + ", my filter=" + mCapabilityFilter);
 
        evalRequest(n);
    }
 
    @VisibleForTesting
    protected void handleRemoveRequest(NetworkRequest request) {
        NetworkRequestInfo n = mNetworkRequests.get(request.requestId);
        if (n != null) {
            mNetworkRequests.remove(request.requestId);
            if (n.requested) releaseNetworkFor(n.request);
        }
    }
 
    private void handleSetScore(int score) {
        mScore = score;
        evalRequests();
    }
 
    private void handleSetFilter(NetworkCapabilities netCap) {
        mCapabilityFilter = netCap;
        evalRequests();
    }
 
    /**
     * Overridable function to provide complex filtering.
     * Called for every request every time a new NetworkRequest is seen
     * and whenever the filterScore or filterNetworkCapabilities change.
     *
     * acceptRequest can be overridden to provide complex filter behavior
     * for the incoming requests
     *
     * For output, this class will call {@link #needNetworkFor} and
     * {@link #releaseNetworkFor} for every request that passes the filters.
     * If you don't need to see every request, you can leave the base
     * implementations of those two functions and instead override
     * {@link #startNetwork} and {@link #stopNetwork}.
     *
     * If you want to see every score fluctuation on every request, set
     * your score filter to a very high number and watch {@link #needNetworkFor}.
     *
     * @return {@code true} to accept the request.
     */
    public boolean acceptRequest(NetworkRequest request, int score) {
        return true;
    }
 
    private void evalRequest(NetworkRequestInfo n) {
        if (VDBG) {
            log("evalRequest");
            log(" n.requests = " + n.requested);
            log(" n.score = " + n.score);
            log(" mScore = " + mScore);
            log(" n.factorySerialNumber = " + n.factorySerialNumber);
            log(" mSerialNumber = " + mSerialNumber);
        }
        if (shouldNeedNetworkFor(n)) {
            if (VDBG) log("  needNetworkFor");
            needNetworkFor(n.request, n.score);
            n.requested = true;
        } else if (shouldReleaseNetworkFor(n)) {
            if (VDBG) log("  releaseNetworkFor");
            releaseNetworkFor(n.request);
            n.requested = false;
        } else {
            if (VDBG) log("  done");
        }
    }
 
    private boolean shouldNeedNetworkFor(NetworkRequestInfo n) {
        // If this request is already tracked, it doesn't qualify for need
        return !n.requested
            // If the score of this request is higher or equal to that of this factory and some
            // other factory is responsible for it, then this factory should not track the request
            // because it has no hope of satisfying it.
            && (n.score < mScore || n.factorySerialNumber == mSerialNumber)
            // If this factory can't satisfy the capability needs of this request, then it
            // should not be tracked.
            && n.request.networkCapabilities.satisfiedByNetworkCapabilities(mCapabilityFilter)
            // Finally if the concrete implementation of the factory rejects the request, then
            // don't track it.
            && acceptRequest(n.request, n.score);
    }
 
    private boolean shouldReleaseNetworkFor(NetworkRequestInfo n) {
        // Don't release a request that's not tracked.
        return n.requested
            // The request should be released if it can't be satisfied by this factory. That
            // means either of the following conditions are met :
            // - Its score is too high to be satisfied by this factory and it's not already
            //   assigned to the factory
            // - This factory can't satisfy the capability needs of the request
            // - The concrete implementation of the factory rejects the request
            && ((n.score > mScore && n.factorySerialNumber != mSerialNumber)
                    || !n.request.networkCapabilities.satisfiedByNetworkCapabilities(
                            mCapabilityFilter)
                    || !acceptRequest(n.request, n.score));
    }
 
    private void evalRequests() {
        for (int i = 0; i < mNetworkRequests.size(); i++) {
            NetworkRequestInfo n = mNetworkRequests.valueAt(i);
            evalRequest(n);
        }
    }
 
    /**
     * Post a command, on this NetworkFactory Handler, to re-evaluate all
     * oustanding requests. Can be called from a factory implementation.
     */
    protected void reevaluateAllRequests() {
        post(() -> {
            evalRequests();
        });
    }
 
    /**
     * Can be called by a factory to release a request as unfulfillable: the request will be
     * removed, and the caller will get a
     * {@link ConnectivityManager.NetworkCallback#onUnavailable()} callback after this function
     * returns.
     *
     * Note: this should only be called by factory which KNOWS that it is the ONLY factory which
     * is able to fulfill this request!
     */
    protected void releaseRequestAsUnfulfillableByAnyFactory(NetworkRequest r) {
        post(() -> {
            if (DBG) log("releaseRequestAsUnfulfillableByAnyFactory: " + r);
            Message msg = obtainMessage(EVENT_UNFULFILLABLE_REQUEST, r);
            if (mAsyncChannel != null) {
                mAsyncChannel.sendMessage(msg);
            } else {
                mPreConnectedQueue.add(msg);
            }
        });
    }
 
    // override to do simple mode (request independent)
    protected void startNetwork() { }
    protected void stopNetwork() { }
 
    // override to do fancier stuff
    protected void needNetworkFor(NetworkRequest networkRequest, int score) {
        if (++mRefCount == 1) startNetwork();
    }
 
    protected void releaseNetworkFor(NetworkRequest networkRequest) {
        if (--mRefCount == 0) stopNetwork();
    }
 
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    public void setScoreFilter(int score) {
        sendMessage(obtainMessage(CMD_SET_SCORE, score, 0));
    }
 
    public void setCapabilityFilter(NetworkCapabilities netCap) {
        sendMessage(obtainMessage(CMD_SET_FILTER, new NetworkCapabilities(netCap)));
    }
 
    @VisibleForTesting
    protected int getRequestCount() {
        return mNetworkRequests.size();
    }
 
    public int getSerialNumber() {
        return mSerialNumber;
    }
 
    protected void log(String s) {
        Log.d(LOG_TAG, s);
    }
 
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
        pw.println(toString());
        pw.increaseIndent();
        for (int i = 0; i < mNetworkRequests.size(); i++) {
            pw.println(mNetworkRequests.valueAt(i));
        }
        pw.decreaseIndent();
    }
 
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{").append(LOG_TAG).append(" - mSerialNumber=")
                .append(mSerialNumber).append(", ScoreFilter=")
                .append(mScore).append(", Filter=").append(mCapabilityFilter).append(", requests=")
                .append(mNetworkRequests.size()).append(", refCount=").append(mRefCount)
                .append("}");
        return sb.toString();
    }
}