aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/ims/rcs/uce/UceDeviceState.java
blob: 93445dbf57c0c01a9233cde60f98527de3f0833b (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
/*
 * Copyright (C) 2021 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.ims.rcs.uce;

import android.annotation.IntDef;
import android.content.Context;
import android.telephony.ims.RcsUceAdapter.ErrorCode;
import android.util.Log;

import com.android.ims.rcs.uce.UceController.RequestType;
import com.android.ims.rcs.uce.UceController.UceControllerCallback;
import com.android.ims.rcs.uce.util.NetworkSipCode;
import com.android.ims.rcs.uce.util.UceUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Manager the device state to determine whether the device is allowed to execute UCE requests or
 * not.
 */
public class UceDeviceState {

    private static final String LOG_TAG = UceUtils.getLogPrefix() + "UceDeviceState";

    /**
     * The device is allowed to execute UCE requests.
     */
    private static final int DEVICE_STATE_OK = 0;

    /**
     * The device will be in the forbidden state when the network response SIP code is 403
     */
    private static final int DEVICE_STATE_FORBIDDEN = 1;

    /**
     * The device will be in the PROVISION error state when the PUBLISH request fails and the
     * SIP code is 404 NOT FOUND.
     */
    private static final int DEVICE_STATE_PROVISION_ERROR = 2;

    /**
     * When the network response SIP code is 489 and the carrier config also indicates that needs
     * to handle the SIP code 489, the device will be in the BAD EVENT state.
     */
    private static final int DEVICE_STATE_BAD_EVENT = 3;

    /**
     * The device will be in the NO_RETRY error state when the PUBLISH request fails and the
     * SIP code is 413 REQUEST ENTITY TOO LARGE.
     */
    private static final int DEVICE_STATE_NO_RETRY = 4;

    @IntDef(value = {
            DEVICE_STATE_OK,
            DEVICE_STATE_FORBIDDEN,
            DEVICE_STATE_PROVISION_ERROR,
            DEVICE_STATE_BAD_EVENT,
            DEVICE_STATE_NO_RETRY,
    }, prefix="DEVICE_STATE_")
    @Retention(RetentionPolicy.SOURCE)
    public @interface DeviceStateType {}

    private static final Map<Integer, String> DEVICE_STATE_DESCRIPTION = new HashMap<>();
    static {
        DEVICE_STATE_DESCRIPTION.put(DEVICE_STATE_OK, "DEVICE_STATE_OK");
        DEVICE_STATE_DESCRIPTION.put(DEVICE_STATE_FORBIDDEN, "DEVICE_STATE_FORBIDDEN");
        DEVICE_STATE_DESCRIPTION.put(DEVICE_STATE_PROVISION_ERROR, "DEVICE_STATE_PROVISION_ERROR");
        DEVICE_STATE_DESCRIPTION.put(DEVICE_STATE_BAD_EVENT, "DEVICE_STATE_BAD_EVENT");
        DEVICE_STATE_DESCRIPTION.put(DEVICE_STATE_NO_RETRY, "DEVICE_STATE_NO_RETRY");
    }

    /**
     * The result of the current device state.
     */
    public static class DeviceStateResult {
        final @DeviceStateType int mDeviceState;
        final @ErrorCode Optional<Integer> mErrorCode;
        final Optional<Instant> mRequestRetryTime;
        final Optional<Instant> mExitStateTime;

        public DeviceStateResult(int deviceState, Optional<Integer> errorCode,
                Optional<Instant> requestRetryTime, Optional<Instant> exitStateTime) {
            mDeviceState = deviceState;
            mErrorCode = errorCode;
            mRequestRetryTime = requestRetryTime;
            mExitStateTime = exitStateTime;
        }

        /**
         * Check current state to see if the UCE request is allowed to be executed.
         */
        public boolean isRequestForbidden() {
            switch(mDeviceState) {
                case DEVICE_STATE_FORBIDDEN:
                case DEVICE_STATE_PROVISION_ERROR:
                case DEVICE_STATE_BAD_EVENT:
                    return true;
                default:
                    return false;
            }
        }

        /**
         * Check current state to see if only the PUBLISH request is allowed to be executed.
         */
        public boolean isPublishRequestBlocked() {
            switch(mDeviceState) {
                case DEVICE_STATE_NO_RETRY:
                    return true;
                default:
                    return false;
            }
        }

        public int getDeviceState() {
            return mDeviceState;
        }

        public Optional<Integer> getErrorCode() {
            return mErrorCode;
        }

        public Optional<Instant> getRequestRetryTime() {
            return mRequestRetryTime;
        }

        public long getRequestRetryAfterMillis() {
            if (!mRequestRetryTime.isPresent()) {
                return 0L;
            }
            long retryAfter = ChronoUnit.MILLIS.between(Instant.now(), mRequestRetryTime.get());
            return (retryAfter < 0L) ? 0L : retryAfter;
        }

        public Optional<Instant> getExitStateTime() {
            return mExitStateTime;
        }

        /**
         * Check if the given DeviceStateResult is equal to current DeviceStateResult instance.
         */
        public boolean isDeviceStateEqual(DeviceStateResult otherDeviceState) {
            if ((mDeviceState == otherDeviceState.getDeviceState()) &&
                    mErrorCode.equals(otherDeviceState.getErrorCode()) &&
                    mRequestRetryTime.equals(otherDeviceState.getRequestRetryTime()) &&
                    mExitStateTime.equals(otherDeviceState.getExitStateTime())) {
                return true;
            }
            return false;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("DeviceState=").append(DEVICE_STATE_DESCRIPTION.get(getDeviceState()))
                    .append(", ErrorCode=").append(getErrorCode())
                    .append(", RetryTime=").append(getRequestRetryTime())
                    .append(", retryAfterMillis=").append(getRequestRetryAfterMillis())
                    .append(", ExitStateTime=").append(getExitStateTime());
            return builder.toString();
        }
    }

    private final int mSubId;
    private final Context mContext;
    private final UceControllerCallback mUceCtrlCallback;

    private @DeviceStateType int mDeviceState;
    private @ErrorCode Optional<Integer> mErrorCode;
    private Optional<Instant> mRequestRetryTime;
    private Optional<Instant> mExitStateTime;

    public UceDeviceState(int subId, Context context, UceControllerCallback uceCtrlCallback) {
        mSubId = subId;
        mContext = context;
        mUceCtrlCallback = uceCtrlCallback;

        // Try to restore the device state from the shared preference.
        boolean restoreFromPref = false;
        Optional<DeviceStateResult> deviceState = UceUtils.restoreDeviceState(mContext, mSubId);
        if (deviceState.isPresent()) {
            restoreFromPref = true;
            mDeviceState = deviceState.get().getDeviceState();
            mErrorCode = deviceState.get().getErrorCode();
            mRequestRetryTime = deviceState.get().getRequestRetryTime();
            mExitStateTime = deviceState.get().getExitStateTime();
        } else {
            mDeviceState = DEVICE_STATE_OK;
            mErrorCode = Optional.empty();
            mRequestRetryTime = Optional.empty();
            mExitStateTime = Optional.empty();
        }
        logd("UceDeviceState: restore from sharedPref=" + restoreFromPref + ", " +
                getCurrentState());
    }

    /**
     * Check and setup the timer to exit the request disallowed state. This method is called when
     * the DeviceState has been initialized completed and need to restore the timer.
     */
    public synchronized void checkSendResetDeviceStateTimer() {
        logd("checkSendResetDeviceStateTimer: time=" + mExitStateTime);
        if (!mExitStateTime.isPresent()) {
            return;
        }
        long expirySec = ChronoUnit.SECONDS.between(Instant.now(), mExitStateTime.get());
        if (expirySec < 0) {
            expirySec = 0;
        }
        // Setup timer to exit the request disallowed state.
        mUceCtrlCallback.setupResetDeviceStateTimer(expirySec);
    }

    /**
     * @return The current device state.
     */
    public synchronized DeviceStateResult getCurrentState() {
        return new DeviceStateResult(mDeviceState, mErrorCode, mRequestRetryTime, mExitStateTime);
    }

    /**
     * Update the device state to determine whether the device is allowed to send requests or not.
     *  @param sipCode The SIP CODE of the request result.
     *  @param reason The reason from the network response.
     *  @param requestType The type of the request.
     */
    public synchronized void refreshDeviceState(int sipCode, String reason,
            @RequestType int requestType) {
        logd("refreshDeviceState: sipCode=" + sipCode + ", reason=" + reason +
                ", requestResponseType=" + UceController.REQUEST_TYPE_DESCRIPTION.get(requestType));

        // Get the current device status before updating the state.
        DeviceStateResult previousState = getCurrentState();

        // Update the device state based on the given sip code.
        switch (sipCode) {
            case NetworkSipCode.SIP_CODE_FORBIDDEN:   // sip 403
            case NetworkSipCode.SIP_CODE_SERVER_TIMEOUT: // sip 504
                if (requestType == UceController.REQUEST_TYPE_PUBLISH) {
                    // Provisioning error for publish request.
                    setDeviceState(DEVICE_STATE_PROVISION_ERROR);
                    updateErrorCode(sipCode, reason, requestType);
                    // There is no request retry time for SIP code 403
                    removeRequestRetryTime();
                    // No timer to exit the forbidden state.
                    removeExitStateTimer();
                }
                break;

            case NetworkSipCode.SIP_CODE_NOT_FOUND:  // sip 404
                // DeviceState only handles 404 NOT FOUND error for PUBLISH request.
                if (requestType == UceController.REQUEST_TYPE_PUBLISH) {
                    setDeviceState(DEVICE_STATE_PROVISION_ERROR);
                    updateErrorCode(sipCode, reason, requestType);
                    // There is no request retry time for SIP code 404
                    removeRequestRetryTime();
                    // No timer to exit this state.
                    removeExitStateTimer();
                }
                break;

            case NetworkSipCode.SIP_CODE_BAD_EVENT:   // sip 489
                if (UceUtils.isRequestForbiddenBySip489(mContext, mSubId)) {
                    setDeviceState(DEVICE_STATE_BAD_EVENT);
                    updateErrorCode(sipCode, reason, requestType);
                    // Setup the request retry time.
                    setupRequestRetryTime();
                    // Setup the timer to exit the BAD EVENT state.
                    setupExitStateTimer();
                }
                break;

            case NetworkSipCode.SIP_CODE_OK:
            case NetworkSipCode.SIP_CODE_ACCEPTED:
                // Reset the device state when the network response is OK.
                resetInternal();
                break;

            case NetworkSipCode.SIP_CODE_REQUEST_ENTITY_TOO_LARGE:   // sip 413
            case NetworkSipCode.SIP_CODE_TEMPORARILY_UNAVAILABLE:   // sip 480
            case NetworkSipCode.SIP_CODE_BUSY:   // sip 486
            case NetworkSipCode.SIP_CODE_SERVER_INTERNAL_ERROR:   // sip 500
            case NetworkSipCode.SIP_CODE_SERVICE_UNAVAILABLE:   // sip 503
            case NetworkSipCode.SIP_CODE_BUSY_EVERYWHERE:   // sip 600
            case NetworkSipCode.SIP_CODE_DECLINE:   // sip 603
                if (requestType == UceController.REQUEST_TYPE_PUBLISH) {
                    setDeviceState(DEVICE_STATE_NO_RETRY);
                    // There is no request retry time for SIP code 413
                    removeRequestRetryTime();
                    // No timer to exit this state.
                    removeExitStateTimer();
                }
                break;
        }

        // Get the updated device state.
        DeviceStateResult currentState = getCurrentState();

        // Remove the device state from the shared preference if the device is allowed to execute
        // UCE requests. Otherwise, save the new state into the shared preference when the device
        // state has changed.
        if (!currentState.isRequestForbidden()) {
            removeDeviceStateFromPreference();
        } else if (!currentState.isDeviceStateEqual(previousState)) {
            saveDeviceStateToPreference(currentState);
        }

        logd("refreshDeviceState: previous: " + previousState + ", current: " + currentState);
    }

    /**
     * Reset the device state. This method is called when the ImsService triggers to send the
     * PUBLISH request.
     */
    public synchronized void resetDeviceState() {
        DeviceStateResult previousState = getCurrentState();
        resetInternal();
        DeviceStateResult currentState = getCurrentState();

        // Remove the device state from shared preference because the device state has been reset.
        removeDeviceStateFromPreference();

        logd("resetDeviceState: previous=" + previousState + ", current=" + currentState);
    }

    /**
     * The internal method to reset the device state. This method doesn't
     */
    private void resetInternal() {
        setDeviceState(DEVICE_STATE_OK);
        resetErrorCode();
        removeRequestRetryTime();
        removeExitStateTimer();
    }

    private void setDeviceState(@DeviceStateType int latestState) {
        if (mDeviceState != latestState) {
            mDeviceState = latestState;
        }
    }

    private void updateErrorCode(int sipCode, String reason, @RequestType int requestType) {
        Optional<Integer> newErrorCode = Optional.of(NetworkSipCode.getCapabilityErrorFromSipCode(
                    sipCode, reason, requestType));
        if (!mErrorCode.equals(newErrorCode)) {
            mErrorCode = newErrorCode;
        }
    }

    private void resetErrorCode() {
        if (mErrorCode.isPresent()) {
            mErrorCode = Optional.empty();
        }
    }

    private void setupRequestRetryTime() {
        /*
         * Update the request retry time when A) it has not been assigned yet or B) it has past the
         * current time and need to be re-assigned a new retry time.
         */
        if (!mRequestRetryTime.isPresent() || mRequestRetryTime.get().isAfter(Instant.now())) {
            long retryInterval = UceUtils.getRequestRetryInterval(mContext, mSubId);
            mRequestRetryTime = Optional.of(Instant.now().plusMillis(retryInterval));
        }
    }

    private void removeRequestRetryTime() {
        if (mRequestRetryTime.isPresent()) {
            mRequestRetryTime = Optional.empty();
        }
    }

    /**
     * Set the timer to exit the device disallowed state and then trigger a PUBLISH request.
     */
    private void setupExitStateTimer() {
        if (!mExitStateTime.isPresent()) {
            long expirySec = UceUtils.getNonRcsCapabilitiesCacheExpiration(mContext, mSubId);
            mExitStateTime = Optional.of(Instant.now().plusSeconds(expirySec));
            logd("setupExitStateTimer: expirationSec=" + expirySec + ", time=" + mExitStateTime);

            // Setup timer to exit the request disallowed state.
            mUceCtrlCallback.setupResetDeviceStateTimer(expirySec);
        }
    }

    /**
     * Remove the exit state timer.
     */
    private void removeExitStateTimer() {
        if (mExitStateTime.isPresent()) {
            mExitStateTime = Optional.empty();
            mUceCtrlCallback.clearResetDeviceStateTimer();
        }
    }

    /**
     * Save the given device sate to the shared preference.
     * @param deviceState
     */
    private void saveDeviceStateToPreference(DeviceStateResult deviceState) {
        boolean result = UceUtils.saveDeviceStateToPreference(mContext, mSubId, deviceState);
        logd("saveDeviceStateToPreference: result=" + result + ", state= " + deviceState);
    }

    /**
     * Remove the device state information from the shared preference because the device is allowed
     * execute UCE requests.
     */
    private void removeDeviceStateFromPreference() {
        boolean result = UceUtils.removeDeviceStateFromPreference(mContext, mSubId);
        logd("removeDeviceStateFromPreference: result=" + result);
    }

    private void logd(String log) {
        Log.d(LOG_TAG, getLogPrefix().append(log).toString());
    }

    private StringBuilder getLogPrefix() {
        StringBuilder builder = new StringBuilder("[");
        builder.append(mSubId);
        builder.append("] ");
        return builder;
    }
}