summaryrefslogtreecommitdiff
path: root/Tethering/src/com/android/networkstack/tethering/TetheringService.java
blob: 9fb61fe4d9ecf61bf45321dc87e1f28c0954a50e (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
/*
 * Copyright (C) 2019 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.networkstack.tethering;

import static android.Manifest.permission.ACCESS_NETWORK_STATE;
import static android.Manifest.permission.NETWORK_SETTINGS;
import static android.Manifest.permission.NETWORK_STACK;
import static android.Manifest.permission.TETHER_PRIVILEGED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
import static android.net.TetheringManager.TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION;
import static android.net.TetheringManager.TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION;
import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
import static android.net.TetheringManager.TETHER_ERROR_UNSUPPORTED;
import static android.net.dhcp.IDhcpServer.STATUS_UNKNOWN_ERROR;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.net.IIntResultListener;
import android.net.INetworkStackConnector;
import android.net.ITetheringConnector;
import android.net.ITetheringEventCallback;
import android.net.NetworkStack;
import android.net.TetheringRequestParcel;
import android.net.dhcp.DhcpServerCallbacks;
import android.net.dhcp.DhcpServingParamsParcel;
import android.net.ip.IpServer;
import android.os.Binder;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.util.Log;

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

import com.android.internal.annotations.VisibleForTesting;
import com.android.networkstack.apishim.SettingsShimImpl;
import com.android.networkstack.apishim.common.SettingsShim;

import java.io.FileDescriptor;
import java.io.PrintWriter;

/**
 * Android service used to manage tethering.
 *
 * <p>The service returns a binder for the system server to communicate with the tethering.
 */
public class TetheringService extends Service {
    private static final String TAG = TetheringService.class.getSimpleName();

    private TetheringConnector mConnector;
    private SettingsShim mSettingsShim;

    @Override
    public void onCreate() {
        final TetheringDependencies deps = makeTetheringDependencies();
        // The Tethering object needs a fully functional context to start, so this can't be done
        // in the constructor.
        mConnector = new TetheringConnector(makeTethering(deps), TetheringService.this);

        mSettingsShim = SettingsShimImpl.newInstance();
    }

    /**
     * Make a reference to Tethering object.
     */
    @VisibleForTesting
    public Tethering makeTethering(TetheringDependencies deps) {
        return new Tethering(deps);
    }

    @NonNull
    @Override
    public IBinder onBind(Intent intent) {
        return mConnector;
    }

    private static class TetheringConnector extends ITetheringConnector.Stub {
        private final TetheringService mService;
        private final Tethering mTethering;

        TetheringConnector(Tethering tether, TetheringService service) {
            mTethering = tether;
            mService = service;
        }

        @Override
        public void tether(String iface, String callerPkg, String callingAttributionTag,
                IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, listener)) return;

            mTethering.tether(iface, IpServer.STATE_TETHERED, listener);
        }

        @Override
        public void untether(String iface, String callerPkg, String callingAttributionTag,
                IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, listener)) return;

            mTethering.untether(iface, listener);
        }

        @Override
        public void setUsbTethering(boolean enable, String callerPkg, String callingAttributionTag,
                IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, listener)) return;

            mTethering.setUsbTethering(enable, listener);
        }

        @Override
        public void startTethering(TetheringRequestParcel request, String callerPkg,
                String callingAttributionTag, IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg,
                    callingAttributionTag,
                    request.exemptFromEntitlementCheck /* onlyAllowPrivileged */,
                    listener)) {
                return;
            }

            mTethering.startTethering(request, listener);
        }

        @Override
        public void stopTethering(int type, String callerPkg, String callingAttributionTag,
                IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, listener)) return;

            try {
                mTethering.stopTethering(type);
                listener.onResult(TETHER_ERROR_NO_ERROR);
            } catch (RemoteException e) { }
        }

        @Override
        public void requestLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
                boolean showEntitlementUi, String callerPkg, String callingAttributionTag) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, receiver)) return;

            mTethering.requestLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
        }

        @Override
        public void registerTetheringEventCallback(ITetheringEventCallback callback,
                String callerPkg) {
            try {
                if (!hasTetherAccessPermission()) {
                    callback.onCallbackStopped(TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION);
                    return;
                }
                mTethering.registerTetheringEventCallback(callback);
            } catch (RemoteException e) { }
        }

        @Override
        public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
                String callerPkg) {
            try {
                if (!hasTetherAccessPermission()) {
                    callback.onCallbackStopped(TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION);
                    return;
                }
                mTethering.unregisterTetheringEventCallback(callback);
            } catch (RemoteException e) { }
        }

        @Override
        public void stopAllTethering(String callerPkg, String callingAttributionTag,
                IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, listener)) return;

            try {
                mTethering.untetherAll();
                listener.onResult(TETHER_ERROR_NO_ERROR);
            } catch (RemoteException e) { }
        }

        @Override
        public void isTetheringSupported(String callerPkg, String callingAttributionTag,
                IIntResultListener listener) {
            if (checkAndNotifyCommonError(callerPkg, callingAttributionTag, listener)) return;

            try {
                listener.onResult(TETHER_ERROR_NO_ERROR);
            } catch (RemoteException e) { }
        }

        @Override
        public void setPreferTestNetworks(boolean prefer, IIntResultListener listener) {
            if (!checkCallingOrSelfPermission(NETWORK_SETTINGS)) {
                try {
                    listener.onResult(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION);
                } catch (RemoteException e) { }
                return;
            }

            mTethering.setPreferTestNetworks(prefer, listener);
        }

        @Override
        protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
                    @Nullable String[] args) {
            mTethering.dump(fd, writer, args);
        }

        private boolean checkAndNotifyCommonError(final String callerPkg,
                final String callingAttributionTag, final IIntResultListener listener) {
            return checkAndNotifyCommonError(callerPkg, callingAttributionTag,
                    false /* onlyAllowPrivileged */, listener);
        }

        private boolean checkAndNotifyCommonError(final String callerPkg,
                final String callingAttributionTag, final boolean onlyAllowPrivileged,
                final IIntResultListener listener) {
            try {
                if (!hasTetherChangePermission(callerPkg, callingAttributionTag,
                        onlyAllowPrivileged)) {
                    listener.onResult(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION);
                    return true;
                }
                if (!mTethering.isTetheringSupported()) {
                    listener.onResult(TETHER_ERROR_UNSUPPORTED);
                    return true;
                }
            } catch (RemoteException e) {
                return true;
            }

            return false;
        }

        private boolean checkAndNotifyCommonError(final String callerPkg,
                final String callingAttributionTag, final ResultReceiver receiver) {
            if (!hasTetherChangePermission(callerPkg, callingAttributionTag,
                    false /* onlyAllowPrivileged */)) {
                receiver.send(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION, null);
                return true;
            }
            if (!mTethering.isTetheringSupported()) {
                receiver.send(TETHER_ERROR_UNSUPPORTED, null);
                return true;
            }

            return false;
        }

        private boolean hasNetworkStackPermission() {
            return checkCallingOrSelfPermission(NETWORK_STACK)
                    || checkCallingOrSelfPermission(PERMISSION_MAINLINE_NETWORK_STACK);
        }

        private boolean hasTetherPrivilegedPermission() {
            return checkCallingOrSelfPermission(TETHER_PRIVILEGED);
        }

        private boolean checkCallingOrSelfPermission(final String permission) {
            return mService.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED;
        }

        private boolean hasTetherChangePermission(final String callerPkg,
                final String callingAttributionTag, final boolean onlyAllowPrivileged) {
            if (onlyAllowPrivileged && !hasNetworkStackPermission()) return false;

            if (hasTetherPrivilegedPermission()) return true;

            if (mTethering.isTetherProvisioningRequired()) return false;

            int uid = Binder.getCallingUid();

            // If callerPkg's uid is not same as Binder.getCallingUid(),
            // checkAndNoteWriteSettingsOperation will return false and the operation will be
            // denied.
            return mService.checkAndNoteWriteSettingsOperation(mService, uid, callerPkg,
                    callingAttributionTag, false /* throwException */);
        }

        private boolean hasTetherAccessPermission() {
            if (hasTetherPrivilegedPermission()) return true;

            return mService.checkCallingOrSelfPermission(
                    ACCESS_NETWORK_STATE) == PERMISSION_GRANTED;
        }
    }

    /**
     * Check if the package is a allowed to write settings. This also accounts that such an access
     * happened.
     *
     * @return {@code true} iff the package is allowed to write settings.
     */
    @VisibleForTesting
    boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
            @NonNull String callingPackage, @Nullable String callingAttributionTag,
            boolean throwException) {
        return mSettingsShim.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
                callingAttributionTag, throwException);
    }

    /**
     * An injection method for testing.
     */
    @VisibleForTesting
    public TetheringDependencies makeTetheringDependencies() {
        return new TetheringDependencies() {
            @Override
            public Looper getTetheringLooper() {
                final HandlerThread tetherThread = new HandlerThread("android.tethering");
                tetherThread.start();
                return tetherThread.getLooper();
            }

            @Override
            public Context getContext() {
                return TetheringService.this;
            }

            @Override
            public IpServer.Dependencies getIpServerDependencies() {
                return new IpServer.Dependencies() {
                    @Override
                    public void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
                            DhcpServerCallbacks cb) {
                        try {
                            final INetworkStackConnector service = getNetworkStackConnector();
                            if (service == null) return;

                            service.makeDhcpServer(ifName, params, cb);
                        } catch (RemoteException e) {
                            Log.e(TAG, "Fail to make dhcp server");
                            try {
                                cb.onDhcpServerCreated(STATUS_UNKNOWN_ERROR, null);
                            } catch (RemoteException re) { }
                        }
                    }
                };
            }

            // TODO: replace this by NetworkStackClient#getRemoteConnector after refactoring
            // networkStackClient.
            static final int NETWORKSTACK_TIMEOUT_MS = 60_000;
            private INetworkStackConnector getNetworkStackConnector() {
                IBinder connector;
                try {
                    final long before = System.currentTimeMillis();
                    while ((connector = NetworkStack.getService()) == null) {
                        if (System.currentTimeMillis() - before > NETWORKSTACK_TIMEOUT_MS) {
                            Log.wtf(TAG, "Timeout, fail to get INetworkStackConnector");
                            return null;
                        }
                        Thread.sleep(200);
                    }
                } catch (InterruptedException e) {
                    Log.wtf(TAG, "Interrupted, fail to get INetworkStackConnector");
                    return null;
                }
                return INetworkStackConnector.Stub.asInterface(connector);
            }

            @Override
            public BluetoothAdapter getBluetoothAdapter() {
                return BluetoothAdapter.getDefaultAdapter();
            }
        };
    }
}