summaryrefslogtreecommitdiff
path: root/com/android/clockwork/bluetooth/CompanionProxyShard.java
blob: 05b0bf81200b4884e1c9a62623a04df13545a06b (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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
package com.android.clockwork.bluetooth;

import android.annotation.AnyThread;
import android.annotation.MainThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.WorkerThread;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.IBluetooth;
import android.bluetooth.IBluetoothManagerCallback;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.ParcelUuid;
import android.os.Process;
import android.os.RemoteException;
import android.util.Log;
import com.android.clockwork.bluetooth.proxy.ProxyServiceManager;
import com.android.clockwork.bluetooth.proxy.WearProxyConstants.Reason;
import com.android.clockwork.common.DebugAssert;
import com.android.clockwork.common.Util;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
import java.io.Closeable;
import java.lang.reflect.Method;

/**
 * Manages connections to the companion sysproxy network
 *
 * This class handles connecting to the remote device using the
 * bluetooth network and configuring the sysproxy to setup the
 * proper network to allow IP traffic to be utilized by Android.
 *
 * Steps to connect to the companion sysproxy.
 *
 * 1. Get a bluetooth rfcomm socket.
 *      This will actually establish a bluetooth connection from the device to the companion.
 * 2. Pass this rfcomm socket to the sysproxy module.
 *      The sysproxy module will formulate the necessary network configuration to allow
 *      IP traffic to flow over the bluetooth socket connection.
 * 3. Get acknowledgement that the sysproxy module initialized.
 *      This may or may not be completed successfully as indicated by the jni callback
 *      indicating connection or failure.
 *
 */
public class CompanionProxyShard implements Closeable, ProxyServiceManager.ProxyServiceCallback {
    private static final String TAG = WearBluetoothConstants.LOG_TAG;
    private static final int WHAT_START_SYSPROXY = 1;
    private static final int WHAT_STOP_SYSPROXY = 2;
    private static final int WHAT_JNI_CONNECTED = 3;
    private static final int WHAT_JNI_DISCONNECTED = 4;
    private static final int WHAT_CONNECTION_FAILED = 5;
    private static final int WHAT_RESET_CONNECTION = 6;

    private static final int INVALID_NETWORK_TYPE = -1;
    private static final int TYPE_RFCOMM = 1;
    private static final int SEC_FLAG_ENCRYPT = 1 << 0;
    private static final int SEC_FLAG_AUTH = 1 << 1;
    // Relative unitless network retry values
    private static final int BACKOFF_BASE_INTERVAL = 2;
    private static final int BACKOFF_BASE_PERIOD = 5;
    private static final int BACKOFF_MAX_INTERVAL = 300;
    private static final ParcelUuid PROXY_UUID =
        ParcelUuid.fromString("fafbdd20-83f0-4389-addf-917ac9dae5b2");

    private static int sInstance;
    private final int mInstance;
    private int mStartAttempts;

    static native void classInitNative();
    @VisibleForTesting native boolean connectNative(int fd);
    @VisibleForTesting native boolean disconnectNative();

    static {
        try {
            System.loadLibrary("wear-bluetooth-jni");
            classInitNative();
        } catch (UnsatisfiedLinkError e) {
            // Invoked during testing
            Log.e(TAG, "Unable to load wear bluetooth sysproxy jni native"
                    + " libraries");
        }
    }

    @NonNull private final Context mContext;
    @NonNull private final BluetoothDevice mCompanionDevice;
    @NonNull private final Listener mListener;
    @NonNull private final ProxyServiceManager mProxyServiceManager;

    private final MultistageExponentialBackoff mReconnectBackoff;
    @VisibleForTesting boolean mIsClosed;

    /** State of sysproxy module process
     *
     * This is a static field because the instance gets
     * created and destroyed by the upper layer based upon
     * specific conditions (e.g. GMS core connected or not)
     *
     * As each instance is created the state of the JNI sysproxy
     * is unknown, so the state of the previous instance is kept here.
     */
    @VisibleForTesting
    static enum State {
        SYSPROXY_DISCONNECTED,  // IDLE or JNI callback
        BLUETOOTH_SOCKET_REQUESTING, // Background thread
        BLUETOOTH_SOCKET_RETRIEVED,
        SYSPROXY_SOCKET_DELIVERING, // Background thread
        SYSPROXY_SOCKET_DELIVERED,
        SYSPROXY_CONNECTED, // JNI callback
        SYSPROXY_DISCONNECT_REQUEST,
        SYSPROXY_DISCONNECT_RESPONSE,
    }

    @VisibleForTesting
    static ProxyState mState = new ProxyState(State.SYSPROXY_DISCONNECTED);

    @VisibleForTesting
    static class ProxyState {
        private State mState;

        public ProxyState(final State state) {
            mState = state;
        }

        @MainThread
        public boolean checkState(final State state) {
            DebugAssert.isMainThread();
            return mState == state;
        }

        @MainThread
        public void advanceState(final int instance, final State state) {
            DebugAssert.isMainThread();
            mState = state;
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "CompanionProxyShard [ " + instance + " ] Set new companion proxy"
                        + " state:" + mState);
            }
        }

        @AnyThread
        public State current() {
            return mState;
        }
    }

    /**
     * Callback executed when the sysproxy becomes connected or disconnected
     *
     * This may send duplicate disconnect events, because failed reconnect
     * attempts are indistinguishable from actual disconnects.
     * Listeners should appropriately deduplicate these disconnect events.
     */
    public interface Listener {
        void onProxyConnectionChange(boolean isConnected, int proxyScore);
    }

    public CompanionProxyShard(
            @NonNull final Context context,
            @NonNull final ProxyServiceManager proxyServiceManager,
            @NonNull final BluetoothDevice companionDevice,
            @NonNull final Listener listener) {
            DebugAssert.isMainThread();

            mContext = context;
            mProxyServiceManager = proxyServiceManager;
            mCompanionDevice = companionDevice;
            mListener = listener;

            mProxyServiceManager.setCallback(this);
            mReconnectBackoff = new MultistageExponentialBackoff(BACKOFF_BASE_INTERVAL,
                    BACKOFF_BASE_PERIOD, BACKOFF_MAX_INTERVAL);

            mInstance = sInstance++;
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Created companion proxy"
                        + " shard");
            }
        }

    /** Completely shuts down companion proxy network */
    @MainThread
    @Override  // Closable
    public void close() {
        DebugAssert.isMainThread();
        if (mIsClosed) {
            Log.w(TAG, "CompanionProxyShard [ " + mInstance + " ] Already closed");
            return;
        }
        mProxyServiceManager.setCallback(null);
        disconnectAndNotify(Reason.CLOSABLE);
        // notify mListeners of our intended disconnect before setting mIsClosed to true
        mIsClosed = true;
        disconnectNativeInBackground();
        mHandler.removeMessages(WHAT_START_SYSPROXY);
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Closed companion proxy shard");
        }
    }

    @MainThread
    @Override  // ProxyServiceManager.ProxyServiceCallback
    public void onStartNetwork() {
        DebugAssert.isMainThread();
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] onStartNetwork()");
        }
        mHandler.sendEmptyMessage(WHAT_START_SYSPROXY);
    }

    @MainThread
    @Override   // ProxyServiceManager.ProxyServiceCallback
    public void onStopNetwork() {
        DebugAssert.isMainThread();
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] onStopNetwork()");
        }
        mHandler.sendEmptyMessage(WHAT_STOP_SYSPROXY);
    }

    @MainThread
    @Override   // ProxyServiceManager.ProxyServiceCallback
    public void onUpdateNetwork(int networkScore) {
        DebugAssert.isMainThread();
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] onUpdateNetwork()");

        }
    }

    /** Serialize state change requests here */
    @VisibleForTesting
    final Handler mHandler = new Handler() {
        @MainThread
        @Override
        public void handleMessage(Message msg) {
            DebugAssert.isMainThread();
            switch (msg.what) {
                case WHAT_START_SYSPROXY:
                    mStartAttempts++;
                    mHandler.removeMessages(WHAT_START_SYSPROXY);
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Request to start"
                                + " companion sysproxy network");
                    }
                    if (mState.checkState(State.SYSPROXY_CONNECTED)) {
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] companion proxy"
                                    + " network already running set connected");
                        }
                        mProxyServiceManager.ensureValidNetworkAgent("Already Connected");
                        connectAndNotify(Reason.SYSPROXY_WAS_CONNECTED);
                    } else if (mState.checkState(State.SYSPROXY_DISCONNECTED)) {
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] companion proxy"
                                    + " network starting up sysproxy module state:"
                                    + mState.current());
                        }
                        mProxyServiceManager.ensureValidNetworkAgent(Reason.START_SYSPROXY);
                        getBluetoothSocket();
                    } else {
                        final int nextRetry = mReconnectBackoff.getNextBackoff();
                        Log.w(TAG, "CompanionProxyShard [ " + mInstance + " ] network not"
                                + " idle/disconnected state:" + mState.current()
                                + " attempting reconnect in " + nextRetry + " seconds");
                        mHandler.sendEmptyMessageDelayed(WHAT_START_SYSPROXY, nextRetry * 1000);
                    }
                    break;
                case WHAT_STOP_SYSPROXY:
                    // If not closed from the upper layer, the proxy will always try maintain a
                    // connection.  However, when the connectivity service decides this network
                    // is unwanted we must break down the current network agent and re-attach
                    // launch with a new network agent.
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Stop companion proxy"
                                + " network");
                    }
                    if (mState.checkState(State.SYSPROXY_CONNECTED)) {
                        disconnectAndNotify(Reason.STOP_SYSPROXY);
                    } else {
                        Log.w(TAG, "CompanionProxyShard [ " + mInstance + " ] companion proxy"
                                + " network not connected! state:" + mState.current());
                    }
                    break;
                case WHAT_JNI_CONNECTED:
                    mReconnectBackoff.reset();
                    mState.advanceState(mInstance, State.SYSPROXY_CONNECTED);
                    break;
                case WHAT_JNI_DISCONNECTED:
                    final int status = msg.arg1;
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI onDisconnect"
                                + " sysproxy closed mIsClosed:" + mIsClosed + " status:" + status);
                    }
                    if (!mIsClosed && mState.current() != State.SYSPROXY_DISCONNECTED) {
                        disconnectAndNotify(Reason.SYSPROXY_DISCONNECTED);
                        setUpRetry();
                    }
                    mState.advanceState(mInstance, State.SYSPROXY_DISCONNECTED);
                    break;
                case WHAT_CONNECTION_FAILED:
                    if (mState.checkState(State.SYSPROXY_CONNECTED)) {
                        Log.e(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI sysproxy failed"
                                + " state:" + mState.current());
                    } else {
                        Log.e(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI sysproxy unable"
                                + " to connect state:" + mState.current());
                    }
                    // fall through
                case WHAT_RESET_CONNECTION:
                    // Take a hammer to reset everything on sysproxy side to initial state.
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Reset companion proxy"
                                + " network connection last state:" + mState.current()
                                + " isClosed:" + mIsClosed);
                    }
                    mHandler.removeMessages(WHAT_START_SYSPROXY);
                    mHandler.removeMessages(WHAT_RESET_CONNECTION);
                    disconnectNativeInBackground();
                    setUpRetry();
                    break;
            }
        }
    };

    private void setUpRetry() {
        // Setup a reconnect sequence if shard has not been closed.
        if (!mIsClosed) {
            final int nextRetry = mReconnectBackoff.getNextBackoff();
            mHandler.sendEmptyMessageDelayed(WHAT_START_SYSPROXY, nextRetry * 1000);
            Log.w(TAG, "CompanionProxyShard [ " + mInstance + " ] Proxy reset"
                    + " Attempting reconnect in " + nextRetry + " seconds");
        }
    }

    /** Use binder API to directly request rfcomm socket from bluetooth module */
    @MainThread
    private void getBluetoothSocket() {
        DebugAssert.isMainThread();

        mState.advanceState(mInstance, State.BLUETOOTH_SOCKET_REQUESTING);
        mProxyServiceManager.setConnecting(Reason.REQUEST_BT_SOCKET);
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Retrieving bluetooth network"
                    + " socket");
        }

        new DefaultPriorityAsyncTask<Void, Void, ParcelFileDescriptor>() {
            @Override
            protected ParcelFileDescriptor doInBackgroundDefaultPriority() {
                try {
                    final IBluetooth bluetoothProxy = getBluetoothService(mInstance);
                    if (bluetoothProxy == null) {
                        Log.e(TAG, "CompanionProxyShard [ " + mInstance + " ] Unable to get binder"
                                + " proxy to IBluetooth");
                        return null;
                    }
                    ParcelFileDescriptor parcelFd = bluetoothProxy.getSocketManager().connectSocket(
                            mCompanionDevice,
                            TYPE_RFCOMM,
                            PROXY_UUID,
                            0 /* port */,
                            SEC_FLAG_AUTH | SEC_FLAG_ENCRYPT
                            );

                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] parcelFd:"
                                + parcelFd);
                    }

                    return parcelFd;
                } catch (RemoteException e) {
                    Log.e(TAG, "CompanionProxyShard [ " + mInstance + " ] Unable to get bluetooth"
                            + " service", e);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(@Nullable ParcelFileDescriptor parcelFd) {
                DebugAssert.isMainThread();

                if (mIsClosed) {
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Shard closed after"
                                + " retrieving bluetooth socket");
                    }
                    return;
                } else if (parcelFd != null) {
                    if (!mState.checkState(State.BLUETOOTH_SOCKET_REQUESTING)) {
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] unexpected state"
                                    + " after retrieving bluetooth network socket state:"
                                    + mState.current());
                        }
                    } else {
                        mState.advanceState(mInstance, State.BLUETOOTH_SOCKET_RETRIEVED);
                        final int fd = parcelFd.detachFd();
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Retrieved"
                                    + " bluetooth network socket state:" + mState.current()
                                    + " parcelFd:" + parcelFd + " fd:" + fd);
                        }
                        connectNativeInBackground(fd);
                    }
                } else {
                    Log.e(TAG, "CompanionProxyShard [ " + mInstance + " ] Unable to request"
                            + "bluetooth network socket");
                    mHandler.sendEmptyMessage(WHAT_RESET_CONNECTION);
                }
                Util.close(parcelFd);
            }
        }.execute();
    }

    @MainThread
    private void connectNativeInBackground(Integer fd) {
        DebugAssert.isMainThread();
        mState.advanceState(mInstance, State.SYSPROXY_SOCKET_DELIVERING);
        mProxyServiceManager.setConnecting(Reason.DELIVER_BT_SOCKET);

        new ConnectSocketAsyncTask() {
            @Override
            protected Boolean doInBackgroundDefaultPriority(Integer fileDescriptor) {
                Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
                final int fd = fileDescriptor.intValue();
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] connectNativeInBackground"
                            + " state:" + mState.current() + " fd:" + fd);
                }
                final boolean rc = connectNative(fd);
                return new Boolean(rc);
            }

            @Override
            protected void onPostExecute(Boolean result) {
                DebugAssert.isMainThread();
                if (mIsClosed) {
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] Shard closed after"
                                + "sending bluetooth socket");
                    }
                    return;
                }
                if (result) {
                    if (!mState.checkState(State.SYSPROXY_SOCKET_DELIVERING)) {
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] unexpected state"
                                    + " after delivering socket state:" + mState.current()
                                    + " fd:" + fd);
                        }
                    } else {
                        mState.advanceState(mInstance, State.SYSPROXY_SOCKET_DELIVERED);
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] proxy socket"
                                    + " delivered state:" + mState.current() + " fd:" + fd);
                        }
                    }
                } else {
                    Log.w(TAG, "CompanionProxyShard [ " + mInstance + " ] Unable to deliver socket"
                            + " to sysproxy module");
                    mHandler.sendEmptyMessage(WHAT_RESET_CONNECTION);
                }
            }
        }.execute(fd);
    }

    /** This call should be idempotent to always ensure proper initial state */
    @MainThread
    private void disconnectNativeInBackground() {
        DebugAssert.isMainThread();
        if (mState.checkState(State.SYSPROXY_DISCONNECTED)) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI has already"
                        + " disconnected");
            }
            return;
        }

        mState.advanceState(mInstance, State.SYSPROXY_DISCONNECT_REQUEST);
        new DefaultPriorityAsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackgroundDefaultPriority() {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI Disconnect request to"
                            + " sysproxy module");
                }
                return disconnectNative();
            }

            @MainThread
            @Override
            protected void onPostExecute(Boolean result) {
                DebugAssert.isMainThread();
                if (result) {
                    mState.advanceState(mInstance, State.SYSPROXY_DISCONNECT_RESPONSE);
                } else {
                    mState.advanceState(mInstance, State.SYSPROXY_DISCONNECTED);
                }
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI Disconnect response"
                            + " result:" + result + " mIsClosed:" + mIsClosed);
                }
            }
        }.execute();
    }

    /**
     * This method is called from JNI in a background thread when the companion proxy
     * network state changes on the phone.
     */
    @WorkerThread
    protected void onActiveNetworkState(final int networkType, final boolean isMetered) {
        if (mIsClosed) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI onActiveNetworkState"
                        + " shard closed...bailing");
            }
            return;
        }

        if (networkType == INVALID_NETWORK_TYPE) {
            mHandler.sendEmptyMessage(WHAT_CONNECTION_FAILED);
        } else {
            connectAndNotify(Reason.SYSPROXY_CONNECTED);
            mProxyServiceManager.setMetered(isMetered);
            mHandler.sendEmptyMessage(WHAT_JNI_CONNECTED);
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "CompanionProxyShard [ " + mInstance + " ] JNI sysproxy process complete"
                        + " state:" + mState.current() + " networkType:" + networkType + " metered:"
                        + isMetered);
            }
        }
    }

    /** This method is called from JNI in a background thread when the proxy has disconnected. */
    @WorkerThread
    protected void onDisconnect(int status) {
        mHandler.sendMessage(mHandler.obtainMessage(WHAT_JNI_DISCONNECTED, status, 0));
    }

    /**
     * These methods notify connectivity service and the upper layers
     * with the current sysproxy state.
     */
    @AnyThread
    private void connectAndNotify(final String reason) {
        mProxyServiceManager.setConnected(reason);
        notifyConnectionChange(true);
    }

    @AnyThread
    private void disconnectAndNotify(final String reason) {
        mProxyServiceManager.setDisconnected(reason);
        notifyConnectionChange(false);
    }

    /**
     * This method notifies mListeners about the state of the sysproxy network.
     *
     *  NOTE: CompanionProxyShard should never call onProxyConnectionChange directly!
     *       Use the notifyConnectionChange method instead.
     */
    @AnyThread
    private void notifyConnectionChange(final boolean isConnected) {
        if (!mIsClosed) {
            mListener.onProxyConnectionChange(isConnected, mProxyServiceManager.getNetworkScore());
        }
    }

    private abstract static class DefaultPriorityAsyncTask<Params, Progress, Result>
            extends AsyncTask<Params, Progress, Result> {

            @Override
            protected Result doInBackground(Params... params) {
                Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
                return doInBackgroundDefaultPriority();
            }

            protected abstract Result doInBackgroundDefaultPriority();
    }

    private abstract static class ConnectSocketAsyncTask extends AsyncTask<Integer, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Integer... params) {
            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
            final Integer fileDescriptor = params[0];
            return doInBackgroundDefaultPriority(fileDescriptor);
        }

        protected abstract Boolean doInBackgroundDefaultPriority(Integer fd);
    }

    /** Returns the shared instance of IBluetooth using reflection (method is package private). */
    private static IBluetooth getBluetoothService(final int instance) {
        try {
            final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            final Method getBluetoothService = adapter.getClass()
                .getDeclaredMethod("getBluetoothService", IBluetoothManagerCallback.class);
            getBluetoothService.setAccessible(true);
            return (IBluetooth) getBluetoothService.invoke(adapter, new Object[] { null });
        } catch (Exception e) {
            Log.e(TAG, "CompanionProxyShard [ " + instance + " ] Error retrieving IBluetooth: ", e);
            return null;
        }
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("CompanionProxyShard: " + mInstance);
        return result.toString();
    }

    public void dump(@NonNull final IndentingPrintWriter ipw) {
        ipw.printf("Companion proxy instance:%d companion device:%s\n", mInstance,
                mCompanionDevice);
        ipw.increaseIndent();
        ipw.printPair("Current state", mState.current());
        ipw.printPair("Is closed", mIsClosed);
        ipw.printPair("Start attempts", mStartAttempts);
        ipw.printPair("Start connection scheduled",
                mHandler.hasMessages(WHAT_START_SYSPROXY));
        ipw.println();
        ipw.decreaseIndent();
        mProxyServiceManager.dump(ipw);
    }
}