aboutsummaryrefslogtreecommitdiff
path: root/src/android/java/com/android/server/thread/openthread/testing/FakeOtDaemon.java
blob: 2a28ed1f1e089e293f0912c03c4f9f34c321c239 (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
/*
 *    Copyright (c) 2023, The OpenThread Authors.
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *    3. Neither the name of the copyright holder nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 */

package com.android.server.thread.openthread.testing;

import static com.android.server.thread.openthread.IOtDaemon.OT_STATE_DISABLED;
import static com.android.server.thread.openthread.IOtDaemon.OT_STATE_ENABLED;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Handler;
import android.os.IBinder;
import android.os.IBinder.DeathRecipient;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;

import com.android.server.thread.openthread.BackboneRouterState;
import com.android.server.thread.openthread.BorderRouterConfigurationParcel;
import com.android.server.thread.openthread.IChannelMasksReceiver;
import com.android.server.thread.openthread.INsdPublisher;
import com.android.server.thread.openthread.IOtDaemon;
import com.android.server.thread.openthread.IOtDaemonCallback;
import com.android.server.thread.openthread.IOtStatusReceiver;
import com.android.server.thread.openthread.MeshcopTxtAttributes;
import com.android.server.thread.openthread.OtDaemonState;

import java.time.Duration;
import java.util.ArrayList;
import java.util.NoSuchElementException;

/** A fake implementation of the {@link IOtDaemon} AIDL API for testing. */
public final class FakeOtDaemon extends IOtDaemon.Stub {
    /** The typical Thread network join / attach delay is around 8 seconds. */
    public static final Duration JOIN_DELAY = Duration.ofSeconds(8);

    static final int OT_DEVICE_ROLE_DISABLED = 0;
    static final int OT_DEVICE_ROLE_DETACHED = 1;
    static final int OT_DEVICE_ROLE_CHILD = 2;
    static final int OT_DEVICE_ROLE_ROUTER = 3;
    static final int OT_DEVICE_ROLE_LEADER = 4;
    static final int OT_ERROR_NONE = 0;

    private static final long PROACTIVE_LISTENER_ID = -1;

    private final Handler mHandler;
    private final OtDaemonState mState;
    private final BackboneRouterState mBbrState;
    private int mThreadEnabled = OT_STATE_ENABLED;
    private int mChannelMasksReceiverOtError = OT_ERROR_NONE;
    private int mSupportedChannelMask = 0x07FFF800; // from channel 11 to 26
    private int mPreferredChannelMask = 0;

    @Nullable private DeathRecipient mDeathRecipient;
    @Nullable private ParcelFileDescriptor mTunFd;
    @Nullable private INsdPublisher mNsdPublisher;
    @Nullable private MeshcopTxtAttributes mOverriddenMeshcopTxts;
    @Nullable private IOtDaemonCallback mCallback;
    @Nullable private Long mCallbackListenerId;
    @Nullable private RemoteException mJoinException;

    public FakeOtDaemon(Handler handler) {
        mHandler = handler;
        mState = new OtDaemonState();
        mState.isInterfaceUp = false;
        mState.deviceRole = OT_DEVICE_ROLE_DISABLED;
        mState.activeDatasetTlvs = new byte[0];
        mState.pendingDatasetTlvs = new byte[0];
        mBbrState = new BackboneRouterState();
        mBbrState.multicastForwardingEnabled = false;
        mBbrState.listeningAddresses = new ArrayList<>();
    }

    @Override
    public IBinder asBinder() {
        return this;
    }

    @Override
    public void linkToDeath(DeathRecipient recipient, int flags) {
        if (mDeathRecipient != null && recipient != null) {
            throw new IllegalStateException("IOtDaemon death recipient is already linked!");
        }

        mDeathRecipient = recipient;
    }

    @Override
    public boolean unlinkToDeath(@NonNull DeathRecipient recipient, int flags) {
        if (mDeathRecipient == null || recipient != mDeathRecipient) {
            throw new NoSuchElementException("recipient is not linked! " + recipient);
        }

        mDeathRecipient = null;
        return true;
    }

    @Override
    public void initialize(
            ParcelFileDescriptor tunFd,
            boolean enabled,
            INsdPublisher nsdPublisher,
            MeshcopTxtAttributes overriddenMeshcopTxts)
            throws RemoteException {
        mTunFd = tunFd;
        mThreadEnabled = enabled ? OT_STATE_ENABLED : OT_STATE_DISABLED;
        mNsdPublisher = nsdPublisher;

        mOverriddenMeshcopTxts = new MeshcopTxtAttributes();
        mOverriddenMeshcopTxts.vendorOui = overriddenMeshcopTxts.vendorOui.clone();
        mOverriddenMeshcopTxts.vendorName = overriddenMeshcopTxts.vendorName;
        mOverriddenMeshcopTxts.modelName = overriddenMeshcopTxts.modelName;
    }

    @Override
    public void setThreadEnabled(boolean enabled, IOtStatusReceiver receiver) {
        mHandler.post(
                () -> {
                    mThreadEnabled = enabled ? OT_STATE_ENABLED : OT_STATE_DISABLED;
                    try {
                        receiver.onSuccess();
                    } catch (RemoteException e) {
                        throw new AssertionError(e);
                    }
                });
    }

    public int getEnabledState() {
        return mThreadEnabled;
    }

    /**
     * Returns the Thread TUN interface FD sent to OT daemon or {@code null} if {@link initialize}
     * is never called.
     */
    @Nullable
    public ParcelFileDescriptor getTunFd() {
        return mTunFd;
    }

    /**
     * Returns the INsdPublisher sent to OT daemon or {@code null} if {@link #initialize} is never
     * called.
     */
    @Nullable
    public INsdPublisher getNsdPublisher() {
        return mNsdPublisher;
    }

    /**
     * Returns the overridden MeshCoP TXT attributes that is to OT daemon or {@code null} if {@link
     * #initialize} is never called.
     */
    @Nullable
    public MeshcopTxtAttributes getOverriddenMeshcopTxtAttributes() {
        return mOverriddenMeshcopTxts;
    }

    @Override
    public void registerStateCallback(IOtDaemonCallback callback, long listenerId)
            throws RemoteException {
        mCallback = callback;
        mCallbackListenerId = listenerId;

        mHandler.post(() -> onStateChanged(mState, mCallbackListenerId));
        mHandler.post(() -> onBackboneRouterStateChanged(mBbrState));
    }

    @Nullable
    public IOtDaemonCallback getStateCallback() {
        return mCallback;
    }

    @Override
    public void join(byte[] activeDataset, IOtStatusReceiver receiver) throws RemoteException {
        if (mJoinException != null) {
            throw mJoinException;
        }

        mHandler.post(
                () -> {
                    mState.isInterfaceUp = true;
                    mState.deviceRole = OT_DEVICE_ROLE_DETACHED;
                    onStateChanged(mState, PROACTIVE_LISTENER_ID);
                });

        mHandler.postDelayed(
                () -> {
                    mState.deviceRole = OT_DEVICE_ROLE_LEADER;
                    mState.activeDatasetTlvs = activeDataset.clone();
                    mBbrState.multicastForwardingEnabled = true;

                    onStateChanged(mState, PROACTIVE_LISTENER_ID);
                    onBackboneRouterStateChanged(mBbrState);
                    try {
                        receiver.onSuccess();
                    } catch (RemoteException e) {
                        throw new AssertionError(e);
                    }
                },
                JOIN_DELAY.toMillis());
    }

    private void onStateChanged(OtDaemonState state, long listenerId) {
        try {
            // Make a copy of state so that clients won't keep a direct reference to it
            OtDaemonState copyState = new OtDaemonState();
            copyState.isInterfaceUp = state.isInterfaceUp;
            copyState.deviceRole = state.deviceRole;
            copyState.partitionId = state.partitionId;
            copyState.activeDatasetTlvs = state.activeDatasetTlvs.clone();
            copyState.pendingDatasetTlvs = state.pendingDatasetTlvs.clone();

            mCallback.onStateChanged(copyState, listenerId);
        } catch (RemoteException e) {
            throw new AssertionError(e);
        }
    }

    private void onBackboneRouterStateChanged(BackboneRouterState state) {
        try {
            // Make a copy of state so that clients won't keep a direct reference to it
            BackboneRouterState copyState = new BackboneRouterState();
            copyState.multicastForwardingEnabled = state.multicastForwardingEnabled;
            copyState.listeningAddresses = new ArrayList<>(state.listeningAddresses);
            mCallback.onBackboneRouterStateChanged(copyState);
        } catch (RemoteException e) {
            throw new AssertionError(e);
        }
    }

    /** Sets the {@link RemoteException} which will be thrown from {@link #join}. */
    public void setJoinException(RemoteException exception) {
        mJoinException = exception;
    }

    @Override
    public void leave(IOtStatusReceiver receiver) throws RemoteException {
        throw new UnsupportedOperationException("FakeOtDaemon#leave is not implemented!");
    }

    @Override
    public void configureBorderRouter(
            BorderRouterConfigurationParcel config, IOtStatusReceiver receiver)
            throws RemoteException {
        throw new UnsupportedOperationException(
                "FakeOtDaemon#configureBorderRouter is not implemented!");
    }

    @Override
    public void scheduleMigration(byte[] pendingDataset, IOtStatusReceiver receiver)
            throws RemoteException {
        throw new UnsupportedOperationException(
                "FakeOtDaemon#scheduleMigration is not implemented!");
    }

    @Override
    public void setCountryCode(String countryCode, IOtStatusReceiver receiver)
            throws RemoteException {
        throw new UnsupportedOperationException("FakeOtDaemon#setCountryCode is not implemented!");
    }

    @Override
    public void getChannelMasks(IChannelMasksReceiver receiver) throws RemoteException {
        mHandler.post(
                () -> {
                    try {
                        if (mChannelMasksReceiverOtError == OT_ERROR_NONE) {
                            receiver.onSuccess(mSupportedChannelMask, mPreferredChannelMask);
                        } else {
                            receiver.onError(
                                    mChannelMasksReceiverOtError, "Get channel masks failed");
                        }
                    } catch (RemoteException e) {
                        throw new AssertionError(e);
                    }
                });
    }

    public void setChannelMasks(int supportedChannelMask, int preferredChannelMask) {
        mSupportedChannelMask = supportedChannelMask;
        mPreferredChannelMask = preferredChannelMask;
    }

    public void setChannelMasksReceiverOtError(int otError) {
        mChannelMasksReceiverOtError = otError;
    }
}