summaryrefslogtreecommitdiff
path: root/tests/java/com/android/server/ethernet/EthernetNetworkFactoryTest.java
blob: 0cd9c1811e64da61d670a67a9380ef738e3f17b9 (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
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
/*
 * 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.ethernet;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.annotation.NonNull;
import android.app.test.MockAnswerUtil.AnswerWithArguments;
import android.content.Context;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.EthernetNetworkSpecifier;
import android.net.IpConfiguration;
import android.net.LinkProperties;
import android.net.NetworkAgentConfig;
import android.net.NetworkCapabilities;
import android.net.NetworkProvider;
import android.net.NetworkRequest;
import android.net.ip.IIpClient;
import android.net.ip.IpClientCallbacks;
import android.net.util.InterfaceParams;
import android.os.Handler;
import android.os.Looper;
import android.os.test.TestLooper;

import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;

import com.android.internal.R;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class EthernetNetworkFactoryTest {
    private TestLooper mLooper = new TestLooper();
    private Handler mHandler;
    private EthernetNetworkFactory mNetFactory = null;
    private IpClientCallbacks mIpClientCallbacks;
    private int mNetworkRequestCount = 0;
    @Mock private Context mContext;
    @Mock private Resources mResources;
    @Mock private EthernetNetworkFactory.Dependencies mDeps;
    @Mock private IIpClient mIpClient;
    @Mock private EthernetNetworkAgent mNetworkAgent;
    @Mock private InterfaceParams mInterfaceParams;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        mHandler = new Handler(mLooper.getLooper());
        mNetworkRequestCount = 0;

        mNetFactory = new EthernetNetworkFactory(mHandler, mContext, createDefaultFilterCaps(),
                mDeps);

        setupNetworkAgentMock();
        setupIpClientMock();
        setupContext();
    }

    private void setupNetworkAgentMock() {
        when(mDeps.makeEthernetNetworkAgent(any(), any(), any(), any(), any(), any(), any()))
                .thenAnswer(new AnswerWithArguments() {
                                       public EthernetNetworkAgent answer(
                                               Context context,
                                               Looper looper,
                                               NetworkCapabilities nc,
                                               LinkProperties lp,
                                               NetworkAgentConfig config,
                                               NetworkProvider provider,
                                               EthernetNetworkAgent.Callbacks cb) {
                                           when(mNetworkAgent.getCallbacks()).thenReturn(cb);
                                           return mNetworkAgent;
                                       }
                                   }
        );
    }

    private void setupIpClientMock() throws Exception {
        doAnswer(inv -> {
            // these tests only support one concurrent IpClient, so make sure we do not accidentally
            // create a mess.
            assertNull("An IpClient has already been created.", mIpClientCallbacks);

            mIpClientCallbacks = inv.getArgument(2);
            mIpClientCallbacks.onIpClientCreated(mIpClient);
            mLooper.dispatchAll();
            return null;
        }).when(mDeps).makeIpClient(any(Context.class), anyString(), any());

        doAnswer(inv -> {
            mIpClientCallbacks.onQuit();
            mLooper.dispatchAll();
            mIpClientCallbacks = null;
            return null;
        }).when(mIpClient).shutdown();
    }

    private void setupContext() {
        when(mContext.getResources()).thenReturn(mResources);
        when(mResources.getString(R.string.config_ethernet_tcp_buffers)).thenReturn(
                "524288,1048576,3145728,524288,1048576,2097152");
    }

    @After
    public void tearDown() {
        // looper is shared with the network agents, so there may still be messages to dispatch on
        // tear down.
        mLooper.dispatchAll();
    }

    private NetworkCapabilities createDefaultFilterCaps() {
        return NetworkCapabilities.Builder.withoutDefaultCapabilities()
                .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                .build();
    }

    private NetworkCapabilities.Builder createInterfaceCapsBuilder(final int transportType) {
        return new NetworkCapabilities.Builder()
                .addTransportType(transportType)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED);
    }

    private NetworkRequest.Builder createDefaultRequestBuilder() {
        return new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    }

    private NetworkRequest createDefaultRequest() {
        return createDefaultRequestBuilder().build();
    }

    private IpConfiguration createDefaultIpConfig() {
        IpConfiguration ipConfig = new IpConfiguration();
        ipConfig.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
        ipConfig.setProxySettings(IpConfiguration.ProxySettings.NONE);
        return ipConfig;
    }

    // creates an interface with provisioning in progress (since updating the interface link state
    // automatically starts the provisioning process)
    private void createInterfaceUndergoingProvisioning(String iface) throws Exception {
        // Default to the ethernet transport type.
        createInterfaceUndergoingProvisioning(iface, NetworkCapabilities.TRANSPORT_ETHERNET);
    }

    private void createInterfaceUndergoingProvisioning(
            @NonNull final String iface, final int transportType) throws Exception {
        mNetFactory.addInterface(iface, iface, createInterfaceCapsBuilder(transportType).build(),
                createDefaultIpConfig());
        assertTrue(mNetFactory.updateInterfaceLinkState(iface, true));
        verify(mDeps).makeIpClient(any(Context.class), anyString(), any());
        verify(mIpClient).startProvisioning(any());
        clearInvocations(mDeps);
        clearInvocations(mIpClient);
    }

    // creates a provisioned interface
    private void createAndVerifyProvisionedInterface(String iface) throws Exception {
        // Default to the ethernet transport type.
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_ETHERNET,
                ConnectivityManager.TYPE_ETHERNET);
    }

    private void createAndVerifyProvisionedInterface(
            @NonNull final String iface, final int transportType, final int expectedLegacyType)
            throws Exception {
        createInterfaceUndergoingProvisioning(iface, transportType);
        mIpClientCallbacks.onProvisioningSuccess(new LinkProperties());
        mLooper.dispatchAll();
        // provisioning succeeded, verify that the network agent is created, registered, marked
        // as connected and legacy type are correctly set.
        verify(mDeps).makeEthernetNetworkAgent(any(), any(), any(), any(),
                argThat(x -> x.getLegacyType() == expectedLegacyType), any(), any());
        verify(mNetworkAgent).register();
        verify(mNetworkAgent).markConnected();
        clearInvocations(mDeps);
        clearInvocations(mNetworkAgent);
    }

    // creates an unprovisioned interface
    private void createUnprovisionedInterface(String iface) throws Exception {
        // the only way to create an unprovisioned interface is by calling needNetworkFor
        // followed by releaseNetworkFor which will stop the NetworkAgent and IpClient. When
        // EthernetNetworkFactory#updateInterfaceLinkState(iface, true) is called, the interface
        // is automatically provisioned even if nobody has ever called needNetworkFor
        createAndVerifyProvisionedInterface(iface);

        // Interface is already provisioned, so startProvisioning / register should not be called
        // again
        mNetFactory.needNetworkFor(createDefaultRequest());
        verify(mIpClient, never()).startProvisioning(any());
        verify(mNetworkAgent, never()).register();

        mNetFactory.releaseNetworkFor(createDefaultRequest());
        verify(mIpClient).shutdown();
        verify(mNetworkAgent).unregister();

        clearInvocations(mIpClient);
        clearInvocations(mNetworkAgent);
    }

    @Test
    public void testAcceptRequest() throws Exception {
        createInterfaceUndergoingProvisioning("eth0");
        assertTrue(mNetFactory.acceptRequest(createDefaultRequest()));

        NetworkRequest wifiRequest = createDefaultRequestBuilder()
                .removeTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
        assertFalse(mNetFactory.acceptRequest(wifiRequest));
    }

    @Test
    public void testUpdateInterfaceLinkStateForActiveProvisioningInterface() throws Exception {
        String iface = "eth0";
        createInterfaceUndergoingProvisioning(iface);
        // verify that the IpClient gets shut down when interface state changes to down.
        assertTrue(mNetFactory.updateInterfaceLinkState(iface, false));
        verify(mIpClient).shutdown();
    }

    @Test
    public void testUpdateInterfaceLinkStateForProvisionedInterface() throws Exception {
        String iface = "eth0";
        createAndVerifyProvisionedInterface(iface);
        assertTrue(mNetFactory.updateInterfaceLinkState(iface, false));
        verify(mIpClient).shutdown();
        verify(mNetworkAgent).unregister();
    }

    @Test
    public void testUpdateInterfaceLinkStateForUnprovisionedInterface() throws Exception {
        String iface = "eth0";
        createUnprovisionedInterface(iface);
        assertTrue(mNetFactory.updateInterfaceLinkState(iface, false));
        // There should not be an active IPClient or NetworkAgent.
        verify(mDeps, never()).makeIpClient(any(), any(), any());
        verify(mDeps, never())
                .makeEthernetNetworkAgent(any(), any(), any(), any(), any(), any(), any());
    }

    @Test
    public void testUpdateInterfaceLinkStateForNonExistingInterface() throws Exception {
        // if interface was never added, link state cannot be updated.
        assertFalse(mNetFactory.updateInterfaceLinkState("eth1", true));
        verify(mDeps, never()).makeIpClient(any(), any(), any());
    }

    @Test
    public void testNeedNetworkForOnProvisionedInterface() throws Exception {
        createAndVerifyProvisionedInterface("eth0");
        mNetFactory.needNetworkFor(createDefaultRequest());
        verify(mIpClient, never()).startProvisioning(any());
    }

    @Test
    public void testNeedNetworkForOnUnprovisionedInterface() throws Exception {
        createUnprovisionedInterface("eth0");
        mNetFactory.needNetworkFor(createDefaultRequest());
        verify(mIpClient).startProvisioning(any());

        mIpClientCallbacks.onProvisioningSuccess(new LinkProperties());
        mLooper.dispatchAll();
        verify(mNetworkAgent).register();
        verify(mNetworkAgent).markConnected();
    }

    @Test
    public void testNeedNetworkForOnInterfaceUndergoingProvisioning() throws Exception {
        createInterfaceUndergoingProvisioning("eth0");
        mNetFactory.needNetworkFor(createDefaultRequest());
        verify(mIpClient, never()).startProvisioning(any());

        mIpClientCallbacks.onProvisioningSuccess(new LinkProperties());
        mLooper.dispatchAll();
        verify(mNetworkAgent).register();
        verify(mNetworkAgent).markConnected();
    }

    @Test
    public void testProvisioningLoss() throws Exception {
        String iface = "eth0";
        when(mDeps.getNetworkInterfaceByName(iface)).thenReturn(mInterfaceParams);
        createAndVerifyProvisionedInterface(iface);

        mIpClientCallbacks.onProvisioningFailure(new LinkProperties());
        mLooper.dispatchAll();
        verify(mIpClient).shutdown();
        verify(mNetworkAgent).unregister();
        // provisioning loss should trigger a retry, since the interface is still there
        verify(mIpClient).startProvisioning(any());
    }

    @Test
    public void testProvisioningLossForDisappearedInterface() throws Exception {
        String iface = "eth0";
        // mocked method returns null by default, but just to be explicit in the test:
        when(mDeps.getNetworkInterfaceByName(eq(iface))).thenReturn(null);

        createAndVerifyProvisionedInterface(iface);
        mIpClientCallbacks.onProvisioningFailure(new LinkProperties());
        mLooper.dispatchAll();
        verify(mIpClient).shutdown();
        verify(mNetworkAgent).unregister();
        // the interface disappeared and getNetworkInterfaceByName returns null, we should not retry
        verify(mIpClient, never()).startProvisioning(any());
    }

    @Test
    public void testIpClientIsNotStartedWhenLinkIsDown() throws Exception {
        String iface = "eth0";
        createUnprovisionedInterface(iface);
        mNetFactory.updateInterfaceLinkState(iface, false);

        mNetFactory.needNetworkFor(createDefaultRequest());

        NetworkRequest specificNetRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                .setNetworkSpecifier(new EthernetNetworkSpecifier(iface))
                .build();
        mNetFactory.needNetworkFor(specificNetRequest);

        // TODO(b/155707957): BUG: IPClient should not be started when the interface link state
        //  is down.
        verify(mDeps).makeIpClient(any(), any(), any());
    }

    @Test
    public void testLinkPropertiesChanged() throws Exception {
        createAndVerifyProvisionedInterface("eth0");

        LinkProperties lp = new LinkProperties();
        mIpClientCallbacks.onLinkPropertiesChange(lp);
        mLooper.dispatchAll();
        verify(mNetworkAgent).sendLinkPropertiesImpl(same(lp));
    }

    @Test
    public void testNetworkUnwanted() throws Exception {
        createAndVerifyProvisionedInterface("eth0");

        mNetworkAgent.getCallbacks().onNetworkUnwanted();
        mLooper.dispatchAll();
        verify(mIpClient).shutdown();
        verify(mNetworkAgent).unregister();
    }

    @Test
    public void testNetworkUnwantedWithStaleNetworkAgent() throws Exception {
        String iface = "eth0";
        // ensures provisioning is restarted after provisioning loss
        when(mDeps.getNetworkInterfaceByName(iface)).thenReturn(mInterfaceParams);
        createAndVerifyProvisionedInterface(iface);

        EthernetNetworkAgent.Callbacks oldCbs = mNetworkAgent.getCallbacks();
        // replace network agent in EthernetNetworkFactory
        // Loss of provisioning will restart the ip client and network agent.
        mIpClientCallbacks.onProvisioningFailure(new LinkProperties());
        mLooper.dispatchAll();
        verify(mDeps).makeIpClient(any(), any(), any());

        mIpClientCallbacks.onProvisioningSuccess(new LinkProperties());
        mLooper.dispatchAll();
        verify(mDeps).makeEthernetNetworkAgent(any(), any(), any(), any(), any(), any(), any());

        // verify that unwanted is ignored
        clearInvocations(mIpClient);
        clearInvocations(mNetworkAgent);
        oldCbs.onNetworkUnwanted();
        verify(mIpClient, never()).shutdown();
        verify(mNetworkAgent, never()).unregister();
    }

    @Test
    public void testTransportOverrideIsCorrectlySet() throws Exception {
        final String iface = "eth0";
        // createProvisionedInterface() has verifications in place for transport override
        // functionality which for EthernetNetworkFactory is network score and legacy type mappings.
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_ETHERNET,
                ConnectivityManager.TYPE_ETHERNET);
        mNetFactory.removeInterface(iface);
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_BLUETOOTH,
                ConnectivityManager.TYPE_BLUETOOTH);
        mNetFactory.removeInterface(iface);
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_WIFI,
                ConnectivityManager.TYPE_WIFI);
        mNetFactory.removeInterface(iface);
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_CELLULAR,
                ConnectivityManager.TYPE_MOBILE);
        mNetFactory.removeInterface(iface);
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_LOWPAN,
                ConnectivityManager.TYPE_NONE);
        mNetFactory.removeInterface(iface);
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_WIFI_AWARE,
                ConnectivityManager.TYPE_NONE);
        mNetFactory.removeInterface(iface);
        createAndVerifyProvisionedInterface(iface, NetworkCapabilities.TRANSPORT_TEST,
                ConnectivityManager.TYPE_NONE);
        mNetFactory.removeInterface(iface);
    }
}