• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* //device/system/reference-ril/reference-ril.c
2 **
3 ** Copyright 2006, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #include <telephony/ril_cdma_sms.h>
19 #include <telephony/librilutils.h>
20 #include <stdio.h>
21 #include <assert.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <sys/cdefs.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <inttypes.h>
29 #include <fcntl.h>
30 #include <pthread.h>
31 #include <alloca.h>
32 #include "atchannel.h"
33 #include "at_tok.h"
34 #include "base64util.h"
35 #include "misc.h"
36 #include <getopt.h>
37 #include <sys/socket.h>
38 #include <cutils/properties.h>
39 #include <cutils/sockets.h>
40 #include <termios.h>
41 #include <sys/wait.h>
42 #include <stdbool.h>
43 #include <net/if.h>
44 #include <netinet/in.h>
45 #include <linux/vm_sockets.h>
46 #include <arpa/inet.h>
47 
48 #include "guest/hals/ril/reference-libril/ril.h"
49 #define LOG_TAG "RIL"
50 #include <utils/Log.h>
51 
noopRemoveWarning(void * a)52 static void *noopRemoveWarning( void *a ) { return a; }
53 #define RIL_UNUSED_PARM(a) noopRemoveWarning((void *)&(a));
54 
55 #define MAX_AT_RESPONSE 0x1000
56 
57 #define MAX_PDP 11  // max LTE bearers
58 
59 /* pathname returned from RIL_REQUEST_SETUP_DATA_CALL / RIL_REQUEST_SETUP_DEFAULT_PDP */
60 // This is used if Wifi is not supported, plain old eth0
61 #ifdef CUTTLEFISH_ENABLE
62 #define PPP_TTY_PATH_ETH0 "buried_eth0"
63 #else
64 #define PPP_TTY_PATH_ETH0 "eth0"
65 #endif
66 // This is used for emulator
67 #define EMULATOR_RADIO_INTERFACE "eth0"
68 
69 // for sim
70 #define AUTH_CONTEXT_EAP_SIM                    128
71 #define AUTH_CONTEXT_EAP_AKA                    129
72 #define SIM_AUTH_RESPONSE_SUCCESS               0
73 #define SIM_AUTH_RESPONSE_SYNC_FAILURE          3
74 
75 // Default MTU value
76 #define DEFAULT_MTU 1500
77 
78 #ifdef USE_TI_COMMANDS
79 
80 // Enable a workaround
81 // 1) Make incoming call, do not answer
82 // 2) Hangup remote end
83 // Expected: call should disappear from CLCC line
84 // Actual: Call shows as "ACTIVE" before disappearing
85 #define WORKAROUND_ERRONEOUS_ANSWER 1
86 
87 // Some variants of the TI stack do not support the +CGEV unsolicited
88 // response. However, they seem to send an unsolicited +CME ERROR: 150
89 #define WORKAROUND_FAKE_CGEV 1
90 #endif
91 
92 /* Modem Technology bits */
93 #define MDM_GSM         0x01
94 #define MDM_WCDMA       0x02
95 #define MDM_CDMA        0x04
96 #define MDM_EVDO        0x08
97 #define MDM_TDSCDMA     0x10
98 #define MDM_LTE         0x20
99 #define MDM_NR          0x40
100 
101 typedef struct {
102     int supportedTechs; // Bitmask of supported Modem Technology bits
103     int currentTech;    // Technology the modem is currently using (in the format used by modem)
104     int isMultimode;
105 
106     // Preferred mode bitmask. This is actually 4 byte-sized bitmasks with different priority values,
107     // in which the byte number from LSB to MSB give the priority.
108     //
109     //          |MSB|   |   |LSB
110     // value:   |00 |00 |00 |00
111     // byte #:  |3  |2  |1  |0
112     //
113     // Higher byte order give higher priority. Thus, a value of 0x0000000f represents
114     // a preferred mode of GSM, WCDMA, CDMA, and EvDo in which all are equally preferrable, whereas
115     // 0x00000201 represents a mode with GSM and WCDMA, in which WCDMA is preferred over GSM
116     int32_t preferredNetworkMode;
117     int subscription_source;
118 
119 } ModemInfo;
120 
121 static ModemInfo *sMdmInfo;
122 // TECH returns the current technology in the format used by the modem.
123 // It can be used as an l-value
124 #define TECH(mdminfo)                 ((mdminfo)->currentTech)
125 // TECH_BIT returns the bitmask equivalent of the current tech
126 #define TECH_BIT(mdminfo)            (1 << ((mdminfo)->currentTech))
127 #define IS_MULTIMODE(mdminfo)         ((mdminfo)->isMultimode)
128 #define TECH_SUPPORTED(mdminfo, tech) ((mdminfo)->supportedTechs & (tech))
129 #define PREFERRED_NETWORK(mdminfo)    ((mdminfo)->preferredNetworkMode)
130 // CDMA Subscription Source
131 #define SSOURCE(mdminfo)              ((mdminfo)->subscription_source)
132 
133 static int net2modem[] = {
134     MDM_GSM | MDM_WCDMA,                                 // 0  - GSM / WCDMA Pref
135     MDM_GSM,                                             // 1  - GSM only
136     MDM_WCDMA,                                           // 2  - WCDMA only
137     MDM_GSM | MDM_WCDMA,                                 // 3  - GSM / WCDMA Auto
138     MDM_CDMA | MDM_EVDO,                                 // 4  - CDMA / EvDo Auto
139     MDM_CDMA,                                            // 5  - CDMA only
140     MDM_EVDO,                                            // 6  - EvDo only
141     MDM_GSM | MDM_WCDMA | MDM_CDMA | MDM_EVDO,           // 7  - GSM/WCDMA, CDMA, EvDo
142     MDM_LTE | MDM_CDMA | MDM_EVDO,                       // 8  - LTE, CDMA and EvDo
143     MDM_LTE | MDM_GSM | MDM_WCDMA,                       // 9  - LTE, GSM/WCDMA
144     MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_GSM | MDM_WCDMA, // 10 - LTE, CDMA, EvDo, GSM/WCDMA
145     MDM_LTE,                                             // 11 - LTE only
146     MDM_LTE | MDM_WCDMA,                                 // 12 - LTE and WCDMA
147     MDM_TDSCDMA,                                         // 13 - TD-SCDMA only
148     MDM_WCDMA | MDM_TDSCDMA,                             // 14 - TD-SCDMA and WCDMA
149     MDM_LTE | MDM_TDSCDMA,                               // 15 - LTE and TD-SCDMA
150     MDM_TDSCDMA | MDM_GSM,                               // 16 - TD-SCDMA and GSM
151     MDM_LTE | MDM_TDSCDMA | MDM_GSM,                     // 17 - TD-SCDMA, GSM and LTE
152     MDM_WCDMA | MDM_TDSCDMA | MDM_GSM,                   // 18 - TD-SCDMA, GSM and WCDMA
153     MDM_LTE | MDM_WCDMA | MDM_TDSCDMA,                   // 19 - LTE, TD-SCDMA and WCDMA
154     MDM_LTE | MDM_WCDMA | MDM_TDSCDMA | MDM_GSM,         // 20 - LTE, TD-SCDMA, GSM, and WCDMA
155     MDM_EVDO | MDM_CDMA | MDM_WCDMA | MDM_TDSCDMA | MDM_GSM,            // 21 - TD-SCDMA, CDMA, EVDO, GSM and WCDMA
156     MDM_LTE | MDM_TDSCDMA | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM,  // 22 - LTE, TDCSDMA, CDMA, EVDO, GSM and WCDMA
157     MDM_NR,                                                             // 23 - NR 5G only mode
158     MDM_NR | MDM_LTE,                                                   // 24 - NR 5G, LTE
159     MDM_NR | MDM_LTE | MDM_CDMA | MDM_EVDO,                             // 25 - NR 5G, LTE, CDMA and EvDo
160     MDM_NR | MDM_LTE | MDM_WCDMA | MDM_GSM,                             // 26 - NR 5G, LTE, GSM and WCDMA
161     MDM_NR | MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM,       // 27 - NR 5G, LTE, CDMA, EvDo, GSM and WCDMA
162     MDM_NR | MDM_LTE | MDM_WCDMA,                                       // 28 - NR 5G, LTE and WCDMA
163     MDM_NR | MDM_LTE | MDM_TDSCDMA,                                     // 29 - NR 5G, LTE and TDSCDMA
164     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_GSM,                           // 30 - NR 5G, LTE, TD-SCDMA and GSM
165     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_WCDMA,                         // 31 - NR 5G, LTE, TD-SCDMA, WCDMA
166     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_WCDMA | MDM_GSM,               // 32 - NR 5G, LTE, TD-SCDMA, GSM and WCDMA
167     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM,  // 33 - NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA
168 };
169 
170 static int32_t net2pmask[] = {
171     MDM_GSM | (MDM_WCDMA << 8),                          // 0  - GSM / WCDMA Pref
172     MDM_GSM,                                             // 1  - GSM only
173     MDM_WCDMA,                                           // 2  - WCDMA only
174     MDM_GSM | MDM_WCDMA,                                 // 3  - GSM / WCDMA Auto
175     MDM_CDMA | MDM_EVDO,                                 // 4  - CDMA / EvDo Auto
176     MDM_CDMA,                                            // 5  - CDMA only
177     MDM_EVDO,                                            // 6  - EvDo only
178     MDM_GSM | MDM_WCDMA | MDM_CDMA | MDM_EVDO,           // 7  - GSM/WCDMA, CDMA, EvDo
179     MDM_LTE | MDM_CDMA | MDM_EVDO,                       // 8  - LTE, CDMA and EvDo
180     MDM_LTE | MDM_GSM | MDM_WCDMA,                       // 9  - LTE, GSM/WCDMA
181     MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_GSM | MDM_WCDMA, // 10 - LTE, CDMA, EvDo, GSM/WCDMA
182     MDM_LTE,                                             // 11 - LTE only
183     MDM_LTE | MDM_WCDMA,                                 // 12 - LTE and WCDMA
184     MDM_TDSCDMA,                                         // 13 - TD-SCDMA only
185     MDM_WCDMA | MDM_TDSCDMA,                             // 14 - TD-SCDMA and WCDMA
186     MDM_LTE | MDM_TDSCDMA,                               // 15 - LTE and TD-SCDMA
187     MDM_TDSCDMA | MDM_GSM,                               // 16 - TD-SCDMA and GSM
188     MDM_LTE | MDM_TDSCDMA | MDM_GSM,                     // 17 - TD-SCDMA, GSM and LTE
189     MDM_WCDMA | MDM_TDSCDMA | MDM_GSM,                   // 18 - TD-SCDMA, GSM and WCDMA
190     MDM_LTE | MDM_WCDMA | MDM_TDSCDMA,                   // 19 - LTE, TD-SCDMA and WCDMA
191     MDM_LTE | MDM_WCDMA | MDM_TDSCDMA | MDM_GSM,         // 20 - LTE, TD-SCDMA, GSM, and WCDMA
192     MDM_EVDO | MDM_CDMA | MDM_WCDMA | MDM_TDSCDMA | MDM_GSM,            // 21 - TD-SCDMA, CDMA, EVDO, GSM and WCDMA
193     MDM_LTE | MDM_TDSCDMA | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM,  // 22 - LTE, TDCSDMA, CDMA, EVDO, GSM and WCDMA
194     MDM_NR,                                                             // 23 - NR 5G only mode
195     MDM_NR | MDM_LTE,                                                   // 24 - NR 5G, LTE
196     MDM_NR | MDM_LTE | MDM_CDMA | MDM_EVDO,                             // 25 - NR 5G, LTE, CDMA and EvDo
197     MDM_NR | MDM_LTE | MDM_WCDMA | MDM_GSM,                             // 26 - NR 5G, LTE, GSM and WCDMA
198     MDM_NR | MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM,       // 27 - NR 5G, LTE, CDMA, EvDo, GSM and WCDMA
199     MDM_NR | MDM_LTE | MDM_WCDMA,                                       // 28 - NR 5G, LTE and WCDMA
200     MDM_NR | MDM_LTE | MDM_TDSCDMA,                                     // 29 - NR 5G, LTE and TDSCDMA
201     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_GSM,                           // 30 - NR 5G, LTE, TD-SCDMA and GSM
202     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_WCDMA,                         // 31 - NR 5G, LTE, TD-SCDMA, WCDMA
203     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_WCDMA | MDM_GSM,               // 32 - NR 5G, LTE, TD-SCDMA, GSM and WCDMA
204     MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM,  // 33 - NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA
205 };
206 
207 #define GSM   (RAF_GSM | RAF_GPRS | RAF_EDGE)
208 #define CDMA  (RAF_IS95A | RAF_IS95B | RAF_1xRTT)
209 #define EVDO  (RAF_EVDO_0 | RAF_EVDO_A | RAF_EVDO_B | RAF_EHRPD)
210 #define WCDMA (RAF_HSUPA | RAF_HSDPA | RAF_HSPA | RAF_HSPAP | RAF_UMTS)
211 #define LTE   (RAF_LTE)
212 #define NR    (RAF_NR)
213 
214 typedef struct {
215     int bitmap;
216     int type;
217 } NetworkTypeBitmap;
218 
219 static NetworkTypeBitmap s_networkMask[] = {
220     {WCDMA | GSM,                     MDM_GSM | (MDM_WCDMA << 8)},                // 0 - GSM / WCDMA Pref
221     {GSM,                             MDM_GSM},                                   // 1 - GSM only
222     {WCDMA,                           MDM_WCDMA},                                 // 2 - WCDMA only
223     {WCDMA | GSM,                     MDM_GSM | MDM_WCDMA},                       // 3 - GSM / WCDMA Auto
224     {CDMA | EVDO,                     MDM_CDMA | MDM_EVDO},                       // 4 - CDMA / EvDo Auto
225     {CDMA,                            MDM_CDMA},                                  // 5 - CDMA only
226     {EVDO,                            MDM_EVDO},                                  // 6 - EvDo only
227     {GSM | WCDMA | CDMA | EVDO,       MDM_GSM | MDM_WCDMA | MDM_CDMA | MDM_EVDO}, // 7 - GSM/WCDMA, CDMA, EvDo
228     {LTE | CDMA | EVDO,               MDM_LTE | MDM_CDMA | MDM_EVDO},             // 8 - LTE, CDMA and EvDo
229     {LTE | GSM | WCDMA,               MDM_LTE | MDM_GSM | MDM_WCDMA},             // 9 - LTE, GSM/WCDMA
230     {LTE | CDMA | EVDO | GSM | WCDMA, MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_GSM | MDM_WCDMA}, // 10 - LTE, CDMA, EvDo, GSM/WCDMA
231     {LTE,                             MDM_LTE},                                             // 11 - LTE only
232     {LTE | WCDMA,                     MDM_LTE | MDM_WCDMA},                                 // 12 - LTE and WCDMA
233     {RAF_TD_SCDMA,                    MDM_TDSCDMA},                                         // 13 - TD-SCDMA only
234     {RAF_TD_SCDMA | WCDMA,            MDM_WCDMA | MDM_TDSCDMA},                             // 14 - TD-SCDMA and WCDMA
235     {LTE | RAF_TD_SCDMA,              MDM_LTE | MDM_TDSCDMA},                               // 15 - LTE and TD-SCDMA
236     {RAF_TD_SCDMA | GSM,              MDM_TDSCDMA | MDM_GSM},                               // 16 - TD-SCDMA and GSM
237     {LTE | RAF_TD_SCDMA | GSM,        MDM_LTE | MDM_TDSCDMA | MDM_GSM},                     // 17 - TD-SCDMA, GSM and LTE
238     {RAF_TD_SCDMA | GSM | WCDMA,      MDM_WCDMA | MDM_TDSCDMA | MDM_GSM},                   // 18 - TD-SCDMA, GSM and WCDMA
239     {LTE | RAF_TD_SCDMA | WCDMA,      MDM_LTE | MDM_WCDMA | MDM_TDSCDMA},                   // 19 - LTE, TD-SCDMA and WCDMA
240     {LTE | RAF_TD_SCDMA | GSM | WCDMA,MDM_LTE | MDM_WCDMA | MDM_TDSCDMA | MDM_GSM},         // 20 - LTE, TD-SCDMA, GSM, and WCDMA
241     {RAF_TD_SCDMA | CDMA | EVDO | GSM | WCDMA,  MDM_EVDO | MDM_CDMA | MDM_WCDMA | MDM_TDSCDMA | MDM_GSM},            // 21 - TD-SCDMA, CDMA, EVDO, GSM and WCDMA
242     {LTE | RAF_TD_SCDMA | CDMA | EVDO | GSM | WCDMA, MDM_LTE | MDM_TDSCDMA | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM},  // 22 - LTE, TDCSDMA, CDMA, EVDO, GSM and WCDMA
243     {NR,                              MDM_NR},                                                             // 23 - NR 5G only mode
244     {NR | LTE,                        MDM_NR | MDM_LTE},                                                   // 24 - NR 5G, LTE
245     {NR | LTE | CDMA | EVDO,          MDM_NR | MDM_LTE | MDM_CDMA | MDM_EVDO},                             // 25 - NR 5G, LTE, CDMA and EvDo
246     {NR | LTE | GSM | WCDMA,          MDM_NR | MDM_LTE | MDM_WCDMA | MDM_GSM},                             // 26 - NR 5G, LTE, GSM and WCDMA
247     {NR | LTE | CDMA | EVDO | GSM | WCDMA, MDM_NR | MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM},  // 27 - NR 5G, LTE, CDMA, EvDo, GSM and WCDMA
248     {NR | LTE | WCDMA,                MDM_NR | MDM_LTE | MDM_WCDMA},                                       // 28 - NR 5G, LTE and WCDMA
249     {NR | LTE | RAF_TD_SCDMA,         MDM_NR | MDM_LTE | MDM_TDSCDMA},                                     // 29 - NR 5G, LTE and TDSCDMA
250     {NR | LTE | RAF_TD_SCDMA | GSM,   MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_GSM},                           // 30 - NR 5G, LTE, TD-SCDMA and GSM
251     {NR | LTE | RAF_TD_SCDMA | WCDMA, MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_WCDMA},                         // 31 - NR 5G, LTE, TD-SCDMA, WCDMA
252     {NR | LTE | RAF_TD_SCDMA | GSM | WCDMA, MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_WCDMA | MDM_GSM},         // 32 - NR 5G, LTE, TD-SCDMA, GSM and WCDMA
253     {NR | LTE | RAF_TD_SCDMA | CDMA | EVDO | GSM | WCDMA, MDM_NR | MDM_LTE | MDM_TDSCDMA | MDM_CDMA | MDM_EVDO | MDM_WCDMA | MDM_GSM},  // 33 - NR 5G, LTE, TD-SCDMA, CDMA, EVDO, GSM and WCDMA
254 };
255 
is3gpp2(int radioTech)256 static int is3gpp2(int radioTech) {
257     switch (radioTech) {
258         case RADIO_TECH_IS95A:
259         case RADIO_TECH_IS95B:
260         case RADIO_TECH_1xRTT:
261         case RADIO_TECH_EVDO_0:
262         case RADIO_TECH_EVDO_A:
263         case RADIO_TECH_EVDO_B:
264         case RADIO_TECH_EHRPD:
265             return 1;
266         default:
267             return 0;
268     }
269 }
270 
271 typedef enum {
272     SIM_ABSENT = 0,
273     SIM_NOT_READY = 1,
274     SIM_READY = 2,
275     SIM_PIN = 3,
276     SIM_PUK = 4,
277     SIM_NETWORK_PERSONALIZATION = 5,
278     RUIM_ABSENT = 6,
279     RUIM_NOT_READY = 7,
280     RUIM_READY = 8,
281     RUIM_PIN = 9,
282     RUIM_PUK = 10,
283     RUIM_NETWORK_PERSONALIZATION = 11,
284     ISIM_ABSENT = 12,
285     ISIM_NOT_READY = 13,
286     ISIM_READY = 14,
287     ISIM_PIN = 15,
288     ISIM_PUK = 16,
289     ISIM_NETWORK_PERSONALIZATION = 17,
290 } SIM_Status;
291 
292 static void onRequest (int request, void *data, size_t datalen, RIL_Token t);
293 static RIL_RadioState currentState();
294 static int onSupports (int requestCode);
295 static void onCancel (RIL_Token t);
296 static const char *getVersion();
297 static int isRadioOn();
298 static SIM_Status getSIMStatus();
299 static int getCardStatus(RIL_CardStatus_v1_5 **pp_card_status);
300 static void freeCardStatus(RIL_CardStatus_v1_5 *p_card_status);
301 static void onDataCallListChanged(void *param);
302 bool areUiccApplicationsEnabled = true;
303 
304 extern const char * requestToString(int request);
305 extern uint8_t hexCharToInt(uint8_t c);
306 extern uint8_t * convertHexStringToBytes(void *response, size_t responseLen);
307 
308 /*** Static Variables ***/
309 static const RIL_RadioFunctions s_callbacks = {
310     RIL_VERSION,
311     onRequest,
312     currentState,
313     onSupports,
314     onCancel,
315     getVersion
316 };
317 
318 #ifdef RIL_SHLIB
319 static const struct RIL_Env *s_rilenv;
320 
321 #define RIL_onRequestComplete(t, e, response, responselen) s_rilenv->OnRequestComplete(t,e, response, responselen)
322 #define RIL_onUnsolicitedResponse(a,b,c) s_rilenv->OnUnsolicitedResponse(a,b,c)
323 #define RIL_requestTimedCallback(a,b,c) s_rilenv->RequestTimedCallback(a,b,c)
324 #endif
325 
326 static RIL_RadioState sState = RADIO_STATE_UNAVAILABLE;
327 static bool isNrDualConnectivityEnabled = true;
328 
329 static pthread_mutex_t s_state_mutex = PTHREAD_MUTEX_INITIALIZER;
330 static pthread_cond_t s_state_cond = PTHREAD_COND_INITIALIZER;
331 
332 static int s_port = -1;
333 static const char * s_device_path = NULL;
334 static int          s_device_socket = 0;
335 static uint32_t s_modem_simulator_port = -1;
336 
337 /* trigger change to this with s_state_cond */
338 static int s_closed = 0;
339 
340 static int sFD;     /* file desc of AT channel */
341 static char sATBuffer[MAX_AT_RESPONSE+1];
342 static char *sATBufferCur = NULL;
343 
344 static const struct timeval TIMEVAL_SIMPOLL = {1,0};
345 static const struct timeval TIMEVAL_CALLSTATEPOLL = {0,500000};
346 static const struct timeval TIMEVAL_0 = {0,0};
347 
348 static int s_ims_registered  = 0;        // 0==unregistered
349 static int s_ims_services    = 1;        // & 0x1 == sms over ims supported
350 static int s_ims_format    = 1;          // FORMAT_3GPP(1) vs FORMAT_3GPP2(2);
351 static int s_ims_cause_retry = 0;        // 1==causes sms over ims to temp fail
352 static int s_ims_cause_perm_failure = 0; // 1==causes sms over ims to permanent fail
353 static int s_ims_gsm_retry   = 0;        // 1==causes sms over gsm to temp fail
354 static int s_ims_gsm_fail    = 0;        // 1==causes sms over gsm to permanent fail
355 
356 #ifdef WORKAROUND_ERRONEOUS_ANSWER
357 // Max number of times we'll try to repoll when we think
358 // we have a AT+CLCC race condition
359 #define REPOLL_CALLS_COUNT_MAX 4
360 
361 // Line index that was incoming or waiting at last poll, or -1 for none
362 static int s_incomingOrWaitingLine = -1;
363 // Number of times we've asked for a repoll of AT+CLCC
364 static int s_repollCallsCount = 0;
365 // Should we expect a call to be answered in the next CLCC?
366 static int s_expectAnswer = 0;
367 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
368 
369 
370 static int s_cell_info_rate_ms = INT_MAX;
371 static int s_mcc = 0;
372 static int s_mnc = 0;
373 static int s_mncLength = 2;
374 static int s_lac = 0;
375 static int s_cid = 0;
376 
377 // STK
378 static bool s_stkServiceRunning = false;
379 static char *s_stkUnsolResponse = NULL;
380 
381 // Next available handle for keep alive session
382 static uint32_t s_session_handle = 1;
383 
384 typedef enum {
385     STK_UNSOL_EVENT_UNKNOWN,
386     STK_UNSOL_EVENT_NOTIFY,
387     STK_UNSOL_PROACTIVE_CMD,
388 } StkUnsolEvent;
389 
390 typedef enum {
391     STK_RUN_AT        = 0x34,
392     STK_SEND_DTMF     = 0x14,
393     STK_SEND_SMS      = 0x13,
394     STK_SEND_SS       = 0x11,
395     STK_SEND_USSD     = 0x12,
396     STK_PLAY_TONE     = 0x20,
397     STK_OPEN_CHANNEL  = 0x40,
398     STK_CLOSE_CHANNEL = 0x41,
399     STK_RECEIVE_DATA  = 0x42,
400     STK_SEND_DATA     = 0x43,
401     STK_GET_CHANNEL_STATUS = 0x44,
402     STK_REFRESH       = 0x01,
403 } StkCmdType;
404 
405 enum PDPState {
406     PDP_IDLE,
407     PDP_BUSY,
408 };
409 
410 struct PDPInfo {
411     int cid;
412     enum PDPState state;
413 };
414 
415 struct PDPInfo s_PDP[] = {
416         {1, PDP_IDLE}, {2, PDP_IDLE}, {3, PDP_IDLE}, {4, PDP_IDLE},  {5, PDP_IDLE},  {6, PDP_IDLE},
417         {7, PDP_IDLE}, {8, PDP_IDLE}, {9, PDP_IDLE}, {10, PDP_IDLE}, {11, PDP_IDLE},
418 };
419 
420 static void pollSIMState (void *param);
421 static void setRadioState(RIL_RadioState newState);
422 static void setRadioTechnology(ModemInfo *mdm, int newtech);
423 static int query_ctec(ModemInfo *mdm, int *current, int32_t *preferred);
424 static int parse_technology_response(const char *response, int *current, int32_t *preferred);
425 static int techFromModemType(int mdmtype);
426 static void getIccId(char *iccid, int size);
427 
clccStateToRILState(int state,RIL_CallState * p_state)428 static int clccStateToRILState(int state, RIL_CallState *p_state)
429 {
430     switch(state) {
431         case 0: *p_state = RIL_CALL_ACTIVE;   return 0;
432         case 1: *p_state = RIL_CALL_HOLDING;  return 0;
433         case 2: *p_state = RIL_CALL_DIALING;  return 0;
434         case 3: *p_state = RIL_CALL_ALERTING; return 0;
435         case 4: *p_state = RIL_CALL_INCOMING; return 0;
436         case 5: *p_state = RIL_CALL_WAITING;  return 0;
437         default: return -1;
438     }
439 }
440 
convertBytesToHexString(char * bin_ptr,int length,unsigned char * hex_ptr)441 void convertBytesToHexString(char *bin_ptr, int length, unsigned char *hex_ptr) {
442     int i;
443     unsigned char tmp;
444 
445     if (bin_ptr == NULL || hex_ptr == NULL) {
446         return;
447     }
448     for (i = 0; i < length; i++) {
449         tmp = (unsigned char)((bin_ptr[i] & 0xf0) >> 4);
450         if (tmp <= 9) {
451             *hex_ptr = (unsigned char)(tmp + '0');
452         } else {
453             *hex_ptr = (unsigned char)(tmp + 'A' - 10);
454         }
455         hex_ptr++;
456         tmp = (unsigned char)(bin_ptr[i] & 0x0f);
457         if (tmp <= 9) {
458             *hex_ptr = (unsigned char)(tmp + '0');
459         } else {
460             *hex_ptr = (unsigned char)(tmp + 'A' - 10);
461         }
462         hex_ptr++;
463     }
464 }
465 
466 /**
467  * Note: directly modified line and has *p_call point directly into
468  * modified line
469  */
callFromCLCCLine(char * line,RIL_Call * p_call)470 static int callFromCLCCLine(char *line, RIL_Call *p_call)
471 {
472         //+CLCC: 1,0,2,0,0,\"+18005551212\",145
473         //     index,isMT,state,mode,isMpty(,number,TOA)?
474 
475     int err;
476     int state;
477     int mode;
478 
479     err = at_tok_start(&line);
480     if (err < 0) goto error;
481 
482     err = at_tok_nextint(&line, &(p_call->index));
483     if (err < 0) goto error;
484 
485     err = at_tok_nextbool(&line, &(p_call->isMT));
486     if (err < 0) goto error;
487 
488     err = at_tok_nextint(&line, &state);
489     if (err < 0) goto error;
490 
491     err = clccStateToRILState(state, &(p_call->state));
492     if (err < 0) goto error;
493 
494     err = at_tok_nextint(&line, &mode);
495     if (err < 0) goto error;
496 
497     p_call->isVoice = (mode == 0);
498 
499     err = at_tok_nextbool(&line, &(p_call->isMpty));
500     if (err < 0) goto error;
501 
502     if (at_tok_hasmore(&line)) {
503         err = at_tok_nextstr(&line, &(p_call->number));
504 
505         /* tolerate null here */
506         if (err < 0) return 0;
507 
508         // Some lame implementations return strings
509         // like "NOT AVAILABLE" in the CLCC line
510         if (p_call->number != NULL
511             && 0 == strspn(p_call->number, "+0123456789")
512         ) {
513             p_call->number = NULL;
514         }
515 
516         err = at_tok_nextint(&line, &p_call->toa);
517         if (err < 0) goto error;
518     }
519 
520     p_call->uusInfo = NULL;
521 
522     return 0;
523 
524 error:
525     RLOGE("invalid CLCC line\n");
526     return -1;
527 }
528 
parseSimResponseLine(char * line,RIL_SIM_IO_Response * response)529 static int parseSimResponseLine(char* line, RIL_SIM_IO_Response* response) {
530     int err;
531 
532     err = at_tok_start(&line);
533     if (err < 0) return err;
534     err = at_tok_nextint(&line, &response->sw1);
535     if (err < 0) return err;
536     err = at_tok_nextint(&line, &response->sw2);
537     if (err < 0) return err;
538 
539     if (at_tok_hasmore(&line)) {
540         err = at_tok_nextstr(&line, &response->simResponse);
541         if (err < 0) return err;
542     }
543     return 0;
544 }
545 
546 #ifdef CUTTLEFISH_ENABLE
set_Ip_Addr(const char * addr,const char * radioInterfaceName)547 static void set_Ip_Addr(const char *addr, const char* radioInterfaceName) {
548   RLOGD("%s %d setting ip addr %s on interface %s", __func__, __LINE__, addr,
549         radioInterfaceName);
550   struct ifreq request;
551   int status = 0;
552   int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
553   if (sock == -1) {
554     RLOGE("Failed to open interface socket: %s (%d)", strerror(errno), errno);
555     return;
556   }
557 
558   memset(&request, 0, sizeof(request));
559   strncpy(request.ifr_name, radioInterfaceName, sizeof(request.ifr_name));
560   request.ifr_name[sizeof(request.ifr_name) - 1] = '\0';
561 
562   char *myaddr = strdup(addr);
563   char *pch = NULL;
564   pch = strchr(myaddr, '/');
565   if (pch) {
566     *pch = '\0';
567   }
568 
569   struct sockaddr_in *sin = (struct sockaddr_in *)&request.ifr_addr;
570   sin->sin_family = AF_INET;
571   sin->sin_addr.s_addr = inet_addr(myaddr);
572   if (ioctl(sock, SIOCSIFADDR, &request) < 0) {
573     RLOGE("%s: failed.", __func__);
574   }
575 
576   close(sock);
577   free(myaddr);
578   RLOGD("%s %d done.", __func__, __LINE__);
579 }
580 #endif
581 
582 enum InterfaceState {
583     kInterfaceUp,
584     kInterfaceDown,
585 };
586 
setInterfaceState(const char * interfaceName,enum InterfaceState state)587 static RIL_Errno setInterfaceState(const char* interfaceName,
588                                    enum InterfaceState state) {
589     struct ifreq request;
590     int status = 0;
591     int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
592     if (sock == -1) {
593         RLOGE("Failed to open interface socket: %s (%d)",
594               strerror(errno), errno);
595         return RIL_E_GENERIC_FAILURE;
596     }
597 
598     memset(&request, 0, sizeof(request));
599     strncpy(request.ifr_name, interfaceName, sizeof(request.ifr_name));
600     request.ifr_name[sizeof(request.ifr_name) - 1] = '\0';
601     status = ioctl(sock, SIOCGIFFLAGS, &request);
602     if (status != 0) {
603         RLOGE("Failed to get interface flags for %s: %s (%d)",
604               interfaceName, strerror(errno), errno);
605         close(sock);
606         return RIL_E_RADIO_NOT_AVAILABLE;
607     }
608 
609     bool isUp = (request.ifr_flags & IFF_UP);
610     if ((state == kInterfaceUp && isUp) || (state == kInterfaceDown && !isUp)) {
611         // Interface already in desired state
612         close(sock);
613         return RIL_E_SUCCESS;
614     }
615 
616     // Simply toggle the flag since we know it's the opposite of what we want
617     request.ifr_flags ^= IFF_UP;
618 
619     status = ioctl(sock, SIOCSIFFLAGS, &request);
620     if (status != 0) {
621         RLOGE("Failed to set interface flags for %s: %s (%d)",
622               interfaceName, strerror(errno), errno);
623         close(sock);
624         return RIL_E_GENERIC_FAILURE;
625     }
626 
627     close(sock);
628     return RIL_E_SUCCESS;
629 }
630 
631 /** do post-AT+CFUN=1 initialization */
onRadioPowerOn()632 static void onRadioPowerOn()
633 {
634 #ifdef USE_TI_COMMANDS
635     /*  Must be after CFUN=1 */
636     /*  TI specific -- notifications for CPHS things such */
637     /*  as CPHS message waiting indicator */
638 
639     at_send_command("AT%CPHS=1", NULL);
640 
641     /*  TI specific -- enable NITZ unsol notifs */
642     at_send_command("AT%CTZV=1", NULL);
643 #endif
644 
645     pollSIMState(NULL);
646 }
647 
648 /** do post- SIM ready initialization */
onSIMReady()649 static void onSIMReady()
650 {
651     at_send_command_singleline("AT+CSMS=1", "+CSMS:", NULL);
652     /*
653      * Always send SMS messages directly to the TE
654      *
655      * mode = 1 // discard when link is reserved (link should never be
656      *             reserved)
657      * mt = 2   // most messages routed to TE
658      * bm = 2   // new cell BM's routed to TE
659      * ds = 1   // Status reports routed to TE
660      * bfr = 1  // flush buffer
661      */
662     at_send_command("AT+CNMI=1,2,2,1,1", NULL);
663 }
664 
requestRadioPower(void * data,size_t datalen __unused,RIL_Token t)665 static void requestRadioPower(void *data, size_t datalen __unused, RIL_Token t)
666 {
667     int onOff;
668 
669     int err;
670     ATResponse *p_response = NULL;
671 
672     assert (datalen >= sizeof(int *));
673     onOff = ((int *)data)[0];
674 
675     if (onOff == 0 && sState != RADIO_STATE_OFF) {
676         err = at_send_command("AT+CFUN=0", &p_response);
677         if (err < 0 || p_response->success == 0) goto error;
678         setRadioState(RADIO_STATE_OFF);
679     } else if (onOff > 0 && sState == RADIO_STATE_OFF) {
680         err = at_send_command("AT+CFUN=1", &p_response);
681         if (err < 0|| p_response->success == 0) {
682             // Some stacks return an error when there is no SIM,
683             // but they really turn the RF portion on
684             // So, if we get an error, let's check to see if it
685             // turned on anyway
686 
687             if (isRadioOn() != 1) {
688                 goto error;
689             }
690         }
691         setRadioState(RADIO_STATE_ON);
692     }
693 
694     at_response_free(p_response);
695     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
696     return;
697 error:
698     at_response_free(p_response);
699     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
700 }
701 
requestShutdown(RIL_Token t)702 static void requestShutdown(RIL_Token t)
703 {
704     int onOff;
705 
706     ATResponse *p_response = NULL;
707 
708     if (sState != RADIO_STATE_OFF) {
709         at_send_command("AT+CFUN=0", &p_response);
710         setRadioState(RADIO_STATE_UNAVAILABLE);
711     }
712 
713     at_response_free(p_response);
714     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
715     return;
716 }
717 
requestNvResetConfig(void * data,size_t datalen __unused,RIL_Token t)718 static void requestNvResetConfig(void* data, size_t datalen __unused, RIL_Token t) {
719     assert(datalen >= sizeof(int*));
720     int nvConfig = ((int*)data)[0];
721     if (nvConfig == 1 /* ResetNvType::RELOAD */) {
722         setRadioState(RADIO_STATE_OFF);
723         // Wait for FW to process radio off before sending radio on for reboot
724         sleep(5);
725         setRadioState(RADIO_STATE_ON);
726     }
727     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
728 }
729 
730 static void requestOrSendDataCallList(int cid, RIL_Token *t);
731 
onDataCallListChanged(void * param __unused)732 static void onDataCallListChanged(void *param __unused)
733 {
734     requestOrSendDataCallList(-1, NULL);
735 }
736 
requestDataCallList(void * data __unused,size_t datalen __unused,RIL_Token t)737 static void requestDataCallList(void *data __unused, size_t datalen __unused, RIL_Token t)
738 {
739     requestOrSendDataCallList(-1, &t);
740 }
741 
742 // Hang up, reject, conference, call waiting
requestCallSelection(void * data __unused,size_t datalen __unused,RIL_Token t,int request)743 static void requestCallSelection(
744                 void *data __unused, size_t datalen __unused, RIL_Token t, int request)
745 {
746     // 3GPP 22.030 6.5.5
747     static char hangupWaiting[]    = "AT+CHLD=0";
748     static char hangupForeground[] = "AT+CHLD=1";
749     static char switchWaiting[]    = "AT+CHLD=2";
750     static char conference[]       = "AT+CHLD=3";
751     static char reject[]           = "ATH";
752 
753     char* atCommand;
754 
755     if (getSIMStatus() == SIM_ABSENT) {
756         RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
757         return;
758     }
759 
760     switch(request) {
761         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
762             // "Releases all held calls or sets User Determined User Busy
763             //  (UDUB) for a waiting call."
764             atCommand = hangupWaiting;
765             break;
766         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
767             // "Releases all active calls (if any exist) and accepts
768             //  the other (held or waiting) call."
769             atCommand = hangupForeground;
770             break;
771         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
772             // "Places all active calls (if any exist) on hold and accepts
773             //  the other (held or waiting) call."
774             atCommand = switchWaiting;
775 #ifdef WORKAROUND_ERRONEOUS_ANSWER
776             s_expectAnswer = 1;
777 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
778             break;
779         case RIL_REQUEST_CONFERENCE:
780             // "Adds a held call to the conversation"
781             atCommand = conference;
782             break;
783         case RIL_REQUEST_UDUB:
784             // User determined user busy (reject)
785             atCommand = reject;
786             break;
787         default:
788             assert(0);
789     }
790     at_send_command(atCommand, NULL);
791     // Success or failure is ignored by the upper layer here.
792     // It will call GET_CURRENT_CALLS and determine success that way.
793     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
794 }
795 
getRadioInterfaceName()796 static const char* getRadioInterfaceName()
797 {
798     if (isInEmulator()) {
799         return EMULATOR_RADIO_INTERFACE;
800     }
801     return PPP_TTY_PATH_ETH0;
802 }
803 
requestOrSendDataCallList(int cid,RIL_Token * t)804 static void requestOrSendDataCallList(int cid, RIL_Token *t)
805 {
806     ATResponse *p_response = NULL;
807     ATLine *p_cur = NULL;
808     int err = -1;
809     int n = 0;
810     char *out = NULL;
811     char propValue[PROP_VALUE_MAX] = {0};
812     const char* radioInterfaceName = getRadioInterfaceName();
813 
814     err = at_send_command_multiline ("AT+CGACT?", "+CGACT:", &p_response);
815     if (err != 0 || p_response->success == 0) {
816         if (t != NULL)
817             RIL_onRequestComplete(*t, RIL_E_GENERIC_FAILURE, NULL, 0);
818         else
819             RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
820                                       NULL, 0);
821         return;
822     }
823 
824     for (p_cur = p_response->p_intermediates; p_cur != NULL;
825          p_cur = p_cur->p_next)
826         n++;
827 
828     RIL_Data_Call_Response_v11 *responses =
829         alloca(n * sizeof(RIL_Data_Call_Response_v11));
830 
831     int i;
832     for (i = 0; i < n; i++) {
833         responses[i].status = -1;
834         responses[i].suggestedRetryTime = -1;
835         responses[i].cid = -1;
836         responses[i].active = -1;
837         responses[i].type = "";
838         responses[i].ifname = "";
839         responses[i].addresses = "";
840         responses[i].dnses = "";
841         responses[i].gateways = "";
842         responses[i].pcscf = "";
843         responses[i].mtu = 0;
844     }
845 
846     RIL_Data_Call_Response_v11 *response = responses;
847     for (p_cur = p_response->p_intermediates; p_cur != NULL;
848          p_cur = p_cur->p_next) {
849         char *line = p_cur->line;
850 
851         err = at_tok_start(&line);
852         if (err < 0)
853             goto error;
854 
855         err = at_tok_nextint(&line, &response->cid);
856         if (err < 0)
857             goto error;
858 
859         err = at_tok_nextint(&line, &response->active);
860         if (err < 0)
861             goto error;
862 
863         response++;
864     }
865 
866     at_response_free(p_response);
867 
868     err = at_send_command_multiline ("AT+CGDCONT?", "+CGDCONT:", &p_response);
869     if (err != 0 || p_response->success == 0) {
870         if (t != NULL)
871             RIL_onRequestComplete(*t, RIL_E_GENERIC_FAILURE, NULL, 0);
872         else
873             RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
874                                       NULL, 0);
875         return;
876     }
877 
878     for (p_cur = p_response->p_intermediates; p_cur != NULL;
879          p_cur = p_cur->p_next) {
880         char *line = p_cur->line;
881         int ncid;
882 
883         err = at_tok_start(&line);
884         if (err < 0)
885             goto error;
886 
887         err = at_tok_nextint(&line, &ncid);
888         if (err < 0)
889             goto error;
890 
891         if (cid != ncid)
892             continue;
893 
894         i = ncid - 1;
895         // Assume no error
896         responses[i].status = 0;
897 
898         // type
899         err = at_tok_nextstr(&line, &out);
900         if (err < 0)
901             goto error;
902 
903         int type_size = strlen(out) + 1;
904         responses[i].type = alloca(type_size);
905         strlcpy(responses[i].type, out, type_size);
906 
907         // APN ignored for v5
908         err = at_tok_nextstr(&line, &out);
909         if (err < 0)
910             goto error;
911 
912         int ifname_size = strlen(radioInterfaceName) + 1;
913         responses[i].ifname = alloca(ifname_size);
914         strlcpy(responses[i].ifname, radioInterfaceName, ifname_size);
915 
916         err = at_tok_nextstr(&line, &out);
917         if (err < 0)
918             goto error;
919 
920         int addresses_size = strlen(out) + 1;
921         responses[i].addresses = alloca(addresses_size);
922         strlcpy(responses[i].addresses, out, addresses_size);
923 #ifdef CUTTLEFISH_ENABLE
924         set_Ip_Addr(responses[i].addresses, radioInterfaceName);
925 #endif
926 
927         if (isInEmulator()) {
928             /* We are in the emulator - the dns servers are listed
929                 * by the following system properties, setup in
930                 * /system/etc/init.goldfish.sh:
931                 *  - vendor.net.eth0.dns1
932                 *  - vendor.net.eth0.dns2
933                 *  - vendor.net.eth0.dns3
934                 *  - vendor.net.eth0.dns4
935                 */
936             const int   dnslist_sz = 128;
937             char*       dnslist = alloca(dnslist_sz);
938             const char* separator = "";
939             int         nn;
940 
941             dnslist[0] = 0;
942             for (nn = 1; nn <= 4; nn++) {
943                 /* Probe vendor.net.eth0.dns<n> */
944                 char  propName[PROP_NAME_MAX];
945                 char  propValue[PROP_VALUE_MAX];
946 
947                 snprintf(propName, sizeof propName, "vendor.net.eth0.dns%d", nn);
948 
949                 /* Ignore if undefined */
950                 if (property_get(propName, propValue, "") <= 0) {
951                     continue;
952                 }
953 
954                 /* Append the DNS IP address */
955                 strlcat(dnslist, separator, dnslist_sz);
956                 strlcat(dnslist, propValue, dnslist_sz);
957                 separator = " ";
958             }
959             responses[i].dnses = dnslist;
960 
961             if (property_get("vendor.net.eth0.gw", propValue, "") > 0) {
962                 responses[i].gateways = propValue;
963             } else {
964                 responses[i].gateways = "";
965             }
966             responses[i].mtu = DEFAULT_MTU;
967         } else {
968             /* I don't know where we are, so use the public Google DNS
969                 * servers by default and no gateway.
970                 */
971             responses[i].dnses = "8.8.8.8 8.8.4.4";
972             responses[i].gateways = "";
973         }
974     }
975 
976     // If cid = -1, return the data call list without processing CGCONTRDP (setupDataCall)
977     if (cid == -1) {
978         if (t != NULL)
979             RIL_onRequestComplete(*t, RIL_E_SUCCESS, &responses[0],
980                                   sizeof(RIL_Data_Call_Response_v11));
981         else
982             RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED, responses,
983                                       n * sizeof(RIL_Data_Call_Response_v11));
984         at_response_free(p_response);
985         p_response = NULL;
986         return;
987     }
988 
989     at_response_free(p_response);
990     p_response = NULL;
991 
992     char cmd[64] = {0};
993     snprintf(cmd, sizeof(cmd), "AT+CGCONTRDP=%d", cid);
994     err = at_send_command_singleline(cmd, "+CGCONTRDP:", &p_response);
995     if (err < 0 || p_response->success == 0) {
996         goto error;
997     }
998 
999     int skip = 0;
1000     char *sskip = NULL;
1001     char *input = p_response->p_intermediates->line;
1002 
1003     int ncid = -1;
1004     err = at_tok_start(&input);
1005     if (err < 0) goto error;
1006 
1007     err = at_tok_nextint(&input, &ncid);  // cid
1008     if (err < 0) goto error;
1009 
1010     if (cid != ncid) goto error;
1011 
1012     i = ncid - 1;
1013 
1014     err = at_tok_nextint(&input, &skip);  // bearer_id
1015     if (err < 0) goto error;
1016 
1017     err = at_tok_nextstr(&input, &sskip);  // apn
1018     if (err < 0) goto error;
1019 
1020     err = at_tok_nextstr(&input, &sskip);  // local_addr_and_subnet_mask
1021     if (err < 0) goto error;
1022 
1023     err = at_tok_nextstr(&input, &responses[i].gateways);  // gw_addr
1024     if (err < 0) goto error;
1025 
1026     err = at_tok_nextstr(&input, &responses[i].dnses);  // dns_prim_addr
1027     if (err < 0) goto error;
1028 
1029     if (t != NULL)
1030         RIL_onRequestComplete(*t, RIL_E_SUCCESS, &responses[i],
1031                                sizeof(RIL_Data_Call_Response_v11));
1032     else
1033         RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
1034                                   responses,
1035                                   n * sizeof(RIL_Data_Call_Response_v11));
1036 
1037     at_response_free(p_response);
1038     return;
1039 
1040 error:
1041     if (t != NULL)
1042         RIL_onRequestComplete(*t, RIL_E_GENERIC_FAILURE, NULL, 0);
1043     else
1044         RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
1045                                   NULL, 0);
1046     at_response_free(p_response);
1047 }
1048 
requestQueryNetworkSelectionMode(void * data __unused,size_t datalen __unused,RIL_Token t)1049 static void requestQueryNetworkSelectionMode(
1050                 void *data __unused, size_t datalen __unused, RIL_Token t)
1051 {
1052     int err;
1053     ATResponse *p_response = NULL;
1054     int response = 0;
1055     char *line;
1056 
1057     err = at_send_command_singleline("AT+COPS?", "+COPS:", &p_response);
1058 
1059     if (err < 0 || p_response->success == 0) {
1060         goto error;
1061     }
1062 
1063     line = p_response->p_intermediates->line;
1064 
1065     err = at_tok_start(&line);
1066 
1067     if (err < 0) {
1068         goto error;
1069     }
1070 
1071     err = at_tok_nextint(&line, &response);
1072 
1073     if (err < 0) {
1074         goto error;
1075     }
1076 
1077     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(int));
1078     at_response_free(p_response);
1079     return;
1080 error:
1081     at_response_free(p_response);
1082     RLOGE("requestQueryNetworkSelectionMode must never return error when radio is on");
1083     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1084 }
1085 
sendCallStateChanged(void * param __unused)1086 static void sendCallStateChanged(void *param __unused)
1087 {
1088     RIL_onUnsolicitedResponse (
1089         RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
1090         NULL, 0);
1091 }
1092 
requestGetCurrentCalls(void * data __unused,size_t datalen __unused,RIL_Token t)1093 static void requestGetCurrentCalls(void *data __unused, size_t datalen __unused, RIL_Token t)
1094 {
1095     int err;
1096     ATResponse *p_response;
1097     ATLine *p_cur;
1098     int countCalls;
1099     int countValidCalls;
1100     RIL_Call *p_calls;
1101     RIL_Call **pp_calls;
1102     int i;
1103     int needRepoll = 0;
1104 
1105 #ifdef WORKAROUND_ERRONEOUS_ANSWER
1106     int prevIncomingOrWaitingLine;
1107 
1108     prevIncomingOrWaitingLine = s_incomingOrWaitingLine;
1109     s_incomingOrWaitingLine = -1;
1110 #endif /*WORKAROUND_ERRONEOUS_ANSWER*/
1111 
1112     err = at_send_command_multiline ("AT+CLCC", "+CLCC:", &p_response);
1113 
1114     if (err != 0 || p_response->success == 0) {
1115         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1116         return;
1117     }
1118 
1119     /* count the calls */
1120     for (countCalls = 0, p_cur = p_response->p_intermediates
1121             ; p_cur != NULL
1122             ; p_cur = p_cur->p_next
1123     ) {
1124         countCalls++;
1125     }
1126 
1127     /* yes, there's an array of pointers and then an array of structures */
1128 
1129     pp_calls = (RIL_Call **)alloca(countCalls * sizeof(RIL_Call *));
1130     p_calls = (RIL_Call *)alloca(countCalls * sizeof(RIL_Call));
1131     memset (p_calls, 0, countCalls * sizeof(RIL_Call));
1132 
1133     /* init the pointer array */
1134     for(i = 0; i < countCalls ; i++) {
1135         pp_calls[i] = &(p_calls[i]);
1136     }
1137 
1138     for (countValidCalls = 0, p_cur = p_response->p_intermediates
1139             ; p_cur != NULL
1140             ; p_cur = p_cur->p_next
1141     ) {
1142         err = callFromCLCCLine(p_cur->line, p_calls + countValidCalls);
1143 
1144         if (err != 0) {
1145             continue;
1146         }
1147 
1148 #ifdef WORKAROUND_ERRONEOUS_ANSWER
1149         if (p_calls[countValidCalls].state == RIL_CALL_INCOMING
1150             || p_calls[countValidCalls].state == RIL_CALL_WAITING
1151         ) {
1152             s_incomingOrWaitingLine = p_calls[countValidCalls].index;
1153         }
1154 #endif /*WORKAROUND_ERRONEOUS_ANSWER*/
1155 
1156         if (p_calls[countValidCalls].state != RIL_CALL_ACTIVE
1157             && p_calls[countValidCalls].state != RIL_CALL_HOLDING
1158         ) {
1159             needRepoll = 1;
1160         }
1161 
1162         countValidCalls++;
1163     }
1164 
1165 #ifdef WORKAROUND_ERRONEOUS_ANSWER
1166     // Basically:
1167     // A call was incoming or waiting
1168     // Now it's marked as active
1169     // But we never answered it
1170     //
1171     // This is probably a bug, and the call will probably
1172     // disappear from the call list in the next poll
1173     if (prevIncomingOrWaitingLine >= 0
1174             && s_incomingOrWaitingLine < 0
1175             && s_expectAnswer == 0
1176     ) {
1177         for (i = 0; i < countValidCalls ; i++) {
1178 
1179             if (p_calls[i].index == prevIncomingOrWaitingLine
1180                     && p_calls[i].state == RIL_CALL_ACTIVE
1181                     && s_repollCallsCount < REPOLL_CALLS_COUNT_MAX
1182             ) {
1183                 RLOGI(
1184                     "Hit WORKAROUND_ERRONOUS_ANSWER case."
1185                     " Repoll count: %d\n", s_repollCallsCount);
1186                 s_repollCallsCount++;
1187                 goto error;
1188             }
1189         }
1190     }
1191 
1192     s_expectAnswer = 0;
1193     s_repollCallsCount = 0;
1194 #endif /*WORKAROUND_ERRONEOUS_ANSWER*/
1195 
1196     RIL_onRequestComplete(t, RIL_E_SUCCESS, pp_calls,
1197             countValidCalls * sizeof (RIL_Call *));
1198 
1199     at_response_free(p_response);
1200 
1201 #ifdef POLL_CALL_STATE
1202     if (countValidCalls) {  // We don't seem to get a "NO CARRIER" message from
1203                             // smd, so we're forced to poll until the call ends.
1204 #else
1205     if (needRepoll) {
1206 #endif
1207         RIL_requestTimedCallback (sendCallStateChanged, NULL, &TIMEVAL_CALLSTATEPOLL);
1208     }
1209 
1210     return;
1211 #ifdef WORKAROUND_ERRONEOUS_ANSWER
1212 error:
1213     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1214     at_response_free(p_response);
1215 #endif
1216 }
1217 
1218 static void requestDial(void *data, size_t datalen __unused, RIL_Token t)
1219 {
1220     RIL_Dial *p_dial;
1221     char *cmd;
1222     const char *clir;
1223 
1224     p_dial = (RIL_Dial *)data;
1225 
1226     switch (p_dial->clir) {
1227         case 1: clir = "I"; break;  /*invocation*/
1228         case 2: clir = "i"; break;  /*suppression*/
1229         default:
1230         case 0: clir = ""; break;   /*subscription default*/
1231     }
1232 
1233     asprintf(&cmd, "ATD%s%s;", p_dial->address, clir);
1234 
1235     at_send_command(cmd, NULL);
1236 
1237     free(cmd);
1238 
1239     /* success or failure is ignored by the upper layer here.
1240        it will call GET_CURRENT_CALLS and determine success that way */
1241     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1242 }
1243 
1244 static void requestWriteSmsToSim(void *data, size_t datalen __unused, RIL_Token t)
1245 {
1246     RIL_SMS_WriteArgs *p_args;
1247     char *cmd;
1248     int length;
1249     int err;
1250     ATResponse *p_response = NULL;
1251 
1252     if (getSIMStatus() == SIM_ABSENT) {
1253         RIL_onRequestComplete(t, RIL_E_SIM_ABSENT, NULL, 0);
1254         return;
1255     }
1256 
1257     p_args = (RIL_SMS_WriteArgs *)data;
1258 
1259     length = strlen(p_args->pdu)/2;
1260     asprintf(&cmd, "AT+CMGW=%d,%d", length, p_args->status);
1261 
1262     err = at_send_command_sms(cmd, p_args->pdu, "+CMGW:", &p_response);
1263 
1264     if (err != 0 || p_response->success == 0) goto error;
1265 
1266     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1267     at_response_free(p_response);
1268 
1269     return;
1270 error:
1271     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1272     at_response_free(p_response);
1273 }
1274 
1275 static void requestHangup(void *data, size_t datalen __unused, RIL_Token t)
1276 {
1277     int *p_line;
1278 
1279     char *cmd;
1280 
1281     if (getSIMStatus() == SIM_ABSENT) {
1282         RIL_onRequestComplete(t, RIL_E_MODEM_ERR, NULL, 0);
1283         return;
1284     }
1285     p_line = (int *)data;
1286 
1287     // 3GPP 22.030 6.5.5
1288     // "Releases a specific active call X"
1289     asprintf(&cmd, "AT+CHLD=1%d", p_line[0]);
1290 
1291     at_send_command(cmd, NULL);
1292 
1293     free(cmd);
1294 
1295     /* success or failure is ignored by the upper layer here.
1296        it will call GET_CURRENT_CALLS and determine success that way */
1297     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1298 }
1299 
1300 static void requestSignalStrength(void *data __unused, size_t datalen __unused, RIL_Token t)
1301 {
1302     ATResponse *p_response = NULL;
1303     int err;
1304     char *line;
1305     int count = 0;
1306     // Accept a response that is at least v6, and up to v12
1307     int minNumOfElements=sizeof(RIL_SignalStrength_v6)/sizeof(int);
1308     int maxNumOfElements=sizeof(RIL_SignalStrength_v12)/sizeof(int);
1309     int response[maxNumOfElements];
1310 
1311     memset(response, 0, sizeof(response));
1312 
1313     // TODO(b/206814247): Rename AT+CSQ command.
1314     err = at_send_command_singleline("AT+CSQ", "+CSQ:", &p_response);
1315 
1316     if (err < 0 || p_response->success == 0) {
1317         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1318         goto error;
1319     }
1320 
1321     line = p_response->p_intermediates->line;
1322 
1323     err = at_tok_start(&line);
1324     if (err < 0) goto error;
1325 
1326     for (count = 0; count < maxNumOfElements; count++) {
1327         err = at_tok_nextint(&line, &(response[count]));
1328         if (err < 0 && count < minNumOfElements) goto error;
1329     }
1330 
1331     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
1332 
1333     at_response_free(p_response);
1334     return;
1335 
1336 error:
1337     RLOGE("requestSignalStrength must never return an error when radio is on");
1338     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1339     at_response_free(p_response);
1340 }
1341 
1342 /**
1343  * networkModePossible. Decides whether the network mode is appropriate for the
1344  * specified modem
1345  */
1346 static int networkModePossible(ModemInfo *mdm, int nm)
1347 {
1348     const int asize = sizeof(net2modem) / sizeof(net2modem[0]);
1349     if (nm >= asize || nm < 0) {
1350         RLOGW("%s %d: invalid net2modem index: %d", __func__, __LINE__, nm);
1351         return 0;
1352     }
1353     if ((net2modem[nm] & mdm->supportedTechs) == net2modem[nm]) {
1354        return 1;
1355     }
1356     return 0;
1357 }
1358 
1359 int getPreferredFromBitmap(int value, int *index) {
1360     for (unsigned int i = 0; i < sizeof(s_networkMask) / sizeof(NetworkTypeBitmap); i++) {
1361         if (s_networkMask[i].bitmap == value) {
1362             if (index) *index = i;
1363             return s_networkMask[i].type;
1364         }
1365     }
1366     // set default value here, since there is no match found
1367     // ref.
1368     //{LTE | GSM | WCDMA,               MDM_LTE | MDM_GSM | MDM_WCDMA},             // 9 - LTE, GSM/WCDMA
1369     //
1370     const int DEFAULT_PREFERRED_INDEX = 9;
1371     const int DEFAULT_PREFERRED_BITMAP = MDM_LTE | MDM_GSM | MDM_WCDMA;
1372     assert(s_networkMask[DEFAULT_PREFERRED_INDEX] == DEFAULT_PREFERRED_BITMAP);
1373     if (index) {
1374         *index = DEFAULT_PREFERRED_INDEX;
1375     }
1376     RLOGD("getPreferredFromBitmap %d not match", value);
1377     return  DEFAULT_PREFERRED_BITMAP;
1378 }
1379 
1380 unsigned getBitmapFromPreferred(int value) {
1381     for (unsigned int i = 0; i < sizeof(s_networkMask) / sizeof(NetworkTypeBitmap); i++) {
1382         if (s_networkMask[i].type == value) {
1383             return s_networkMask[i].bitmap;
1384         }
1385     }
1386     RLOGD("getBitmapFromPreferred %d not match", value);
1387     return  LTE | GSM | WCDMA;
1388 }
1389 
1390 static void requestSetPreferredNetworkType(int request, void *data,
1391                                            size_t datalen __unused, RIL_Token t )
1392 {
1393     ATResponse *p_response = NULL;
1394     char *cmd = NULL;
1395     int value = *(int *)data;
1396     int index = value;
1397     int current, old;
1398     int err;
1399     int32_t preferred;
1400 
1401     if (request == RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE) {
1402         preferred = net2pmask[value];
1403     } else {
1404         preferred = getPreferredFromBitmap(value, &index);
1405     }
1406     RLOGD("requestSetPreferredNetworkType: current: %x. New: %x", PREFERRED_NETWORK(sMdmInfo), preferred);
1407 
1408     if (!networkModePossible(sMdmInfo, index)) {
1409         RIL_onRequestComplete(t, RIL_E_MODE_NOT_SUPPORTED, NULL, 0);
1410         return;
1411     }
1412 
1413     if (query_ctec(sMdmInfo, &current, NULL) < 0) {
1414         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1415         return;
1416     }
1417     old = PREFERRED_NETWORK(sMdmInfo);
1418     RLOGD("old != preferred: %d", old != preferred);
1419     if (old != preferred) {
1420         asprintf(&cmd, "AT+CTEC=%d,\"%x\"", current, preferred);
1421         RLOGD("Sending command: <%s>", cmd);
1422         err = at_send_command_singleline(cmd, "+CTEC:", &p_response);
1423         free(cmd);
1424         if (err || !p_response->success) {
1425             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1426             return;
1427         }
1428         PREFERRED_NETWORK(sMdmInfo) = value;
1429         if (!strstr( p_response->p_intermediates->line, "DONE") ) {
1430             int current;
1431             int res = parse_technology_response(p_response->p_intermediates->line, &current, NULL);
1432             switch (res) {
1433                 case -1: // Error or unable to parse
1434                     break;
1435                 case 1: // Only able to parse current
1436                 case 0: // Both current and preferred were parsed
1437                     setRadioTechnology(sMdmInfo, current);
1438                     break;
1439             }
1440         }
1441     }
1442     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1443 }
1444 
1445 static void requestGetPreferredNetworkType(int request __unused, void *data __unused,
1446                                    size_t datalen __unused, RIL_Token t)
1447 {
1448     int preferred;
1449     unsigned i;
1450 
1451     switch ( query_ctec(sMdmInfo, NULL, &preferred) ) {
1452         case -1: // Error or unable to parse
1453         case 1: // Only able to parse current
1454             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1455             break;
1456         case 0: // Both current and preferred were parsed
1457             for ( i = 0 ; i < sizeof(net2pmask) / sizeof(int32_t) ; i++ ) {
1458                 if (preferred == net2pmask[i]) {
1459                     goto done;
1460                 }
1461             }
1462             RLOGE("Unknown preferred mode received from modem: %d", preferred);
1463             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1464             return;
1465     }
1466 done:
1467     if (request == RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE_BITMAP ||
1468             request == RIL_REQUEST_GET_ALLOWED_NETWORK_TYPES_BITMAP) {
1469         i = getBitmapFromPreferred(preferred);
1470     }
1471     RIL_onRequestComplete(t, RIL_E_SUCCESS, &i, sizeof(i));
1472 }
1473 
1474 static void requestGetCarrierRestrictions(void* data, size_t datalen, RIL_Token t) {
1475     RIL_UNUSED_PARM(datalen);
1476     RIL_UNUSED_PARM(data);
1477 
1478     // Fixed values. TODO: query modem
1479     RIL_Carrier allowed_carriers = {
1480             "123",          // mcc
1481             "456",          // mnc
1482             RIL_MATCH_ALL,  // match_type
1483             "",             // match_data
1484     };
1485 
1486     RIL_Carrier excluded_carriers;
1487 
1488     RIL_CarrierRestrictionsWithPriority restrictions = {
1489             1,                   // len_allowed_carriers
1490             0,                   // len_excluded_carriers
1491             &allowed_carriers,   // allowed_carriers
1492             &excluded_carriers,  // excluded_carriers
1493             1,                   // allowedCarriersPrioritized
1494             NO_MULTISIM_POLICY   // multiSimPolicy
1495     };
1496 
1497     RIL_onRequestComplete(t, RIL_E_SUCCESS, &restrictions, sizeof(restrictions));
1498 }
1499 
1500 static void requestCdmaPrlVersion(int request __unused, void *data __unused,
1501                                    size_t datalen __unused, RIL_Token t)
1502 {
1503     int err;
1504     char * responseStr;
1505     ATResponse *p_response = NULL;
1506     const char *cmd;
1507     char *line;
1508 
1509     err = at_send_command_singleline("AT+WPRL?", "+WPRL:", &p_response);
1510     if (err < 0 || !p_response->success) goto error;
1511     line = p_response->p_intermediates->line;
1512     err = at_tok_start(&line);
1513     if (err < 0) goto error;
1514     err = at_tok_nextstr(&line, &responseStr);
1515     if (err < 0 || !responseStr) goto error;
1516     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, strlen(responseStr));
1517     at_response_free(p_response);
1518     return;
1519 error:
1520     at_response_free(p_response);
1521     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1522 }
1523 
1524 static void requestCdmaBaseBandVersion(int request __unused, void *data __unused,
1525                                    size_t datalen __unused, RIL_Token t)
1526 {
1527     int err;
1528     char * responseStr;
1529     ATResponse *p_response = NULL;
1530     const char *cmd;
1531     const char *prefix;
1532     char *line, *p;
1533     int commas;
1534     int skip;
1535     int count = 4;
1536 
1537     // Fixed values. TODO: query modem
1538     responseStr = strdup("1.0.0.0");
1539     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, sizeof(responseStr));
1540     free(responseStr);
1541 }
1542 
1543 static void requestDeviceIdentity(int request __unused, void *data __unused,
1544                                         size_t datalen __unused, RIL_Token t)
1545 {
1546     int err;
1547     int response[4];
1548     char * responseStr[4];
1549     ATResponse *p_response = NULL;
1550     const char *cmd;
1551     const char *prefix;
1552     char *line, *p;
1553     int commas;
1554     int skip;
1555     int count = 4;
1556 
1557     // Fixed values. TODO: Query modem
1558     responseStr[0] ="358240051111110";
1559     responseStr[1] =  "";
1560     responseStr[2] = "77777777";
1561     responseStr[3] = ""; // default empty for non-CDMA
1562 
1563     err = at_send_command_numeric("AT+CGSN", &p_response);
1564     if (err < 0 || p_response->success == 0) {
1565         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1566         return;
1567     } else {
1568         if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
1569             responseStr[3] = p_response->p_intermediates->line;
1570         } else {
1571             responseStr[0] = p_response->p_intermediates->line;
1572         }
1573     }
1574 
1575     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, count*sizeof(char*));
1576     at_response_free(p_response);
1577 }
1578 
1579 static void requestCdmaGetSubscriptionSource(int request __unused, void *data,
1580                                         size_t datalen __unused, RIL_Token t)
1581 {
1582     int err;
1583     int *ss = (int *)data;
1584     ATResponse *p_response = NULL;
1585     char *cmd = NULL;
1586     char *line = NULL;
1587     int response;
1588 
1589     asprintf(&cmd, "AT+CCSS?");
1590     if (!cmd) goto error;
1591 
1592     err = at_send_command_singleline(cmd, "+CCSS:", &p_response);
1593     if (err < 0 || !p_response->success)
1594         goto error;
1595 
1596     line = p_response->p_intermediates->line;
1597     err = at_tok_start(&line);
1598     if (err < 0) goto error;
1599 
1600     err = at_tok_nextint(&line, &response);
1601     free(cmd);
1602     cmd = NULL;
1603 
1604     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
1605 
1606     return;
1607 error:
1608     free(cmd);
1609     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1610 }
1611 
1612 static void requestCdmaSetSubscriptionSource(int request __unused, void *data,
1613                                         size_t datalen, RIL_Token t)
1614 {
1615     int err;
1616     int *ss = (int *)data;
1617     ATResponse *p_response = NULL;
1618     char *cmd = NULL;
1619 
1620     if (!ss || !datalen) {
1621         RLOGE("RIL_REQUEST_CDMA_SET_SUBSCRIPTION without data!");
1622         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1623         return;
1624     }
1625     asprintf(&cmd, "AT+CCSS=%d", ss[0]);
1626     if (!cmd) goto error;
1627 
1628     err = at_send_command(cmd, &p_response);
1629     if (err < 0 || !p_response->success)
1630         goto error;
1631     free(cmd);
1632     cmd = NULL;
1633 
1634     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1635 
1636     RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED, ss, sizeof(ss[0]));
1637 
1638     return;
1639 error:
1640     free(cmd);
1641     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1642 }
1643 
1644 static void requestCdmaSubscription(int request __unused, void *data __unused,
1645                                         size_t datalen __unused, RIL_Token t)
1646 {
1647     int err;
1648     int response[5];
1649     char * responseStr[5];
1650     ATResponse *p_response = NULL;
1651     const char *cmd;
1652     const char *prefix;
1653     char *line, *p;
1654     int commas;
1655     int skip;
1656     int count = 5;
1657 
1658     // Fixed values. TODO: Query modem
1659     responseStr[0] = "8587777777"; // MDN
1660     responseStr[1] = "1"; // SID
1661     responseStr[2] = "1"; // NID
1662     responseStr[3] = "8587777777"; // MIN
1663     responseStr[4] = "1"; // PRL Version
1664     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, count*sizeof(char*));
1665 }
1666 
1667 static void requestCdmaGetRoamingPreference(int request __unused, void *data __unused,
1668                                                  size_t datalen __unused, RIL_Token t)
1669 {
1670     int roaming_pref = -1;
1671     ATResponse *p_response = NULL;
1672     char *line;
1673     int res;
1674 
1675     res = at_send_command_singleline("AT+WRMP?", "+WRMP:", &p_response);
1676     if (res < 0 || !p_response->success) {
1677         goto error;
1678     }
1679     line = p_response->p_intermediates->line;
1680 
1681     res = at_tok_start(&line);
1682     if (res < 0) goto error;
1683 
1684     res = at_tok_nextint(&line, &roaming_pref);
1685     if (res < 0) goto error;
1686 
1687     RIL_onRequestComplete(t, RIL_E_SUCCESS, &roaming_pref, sizeof(roaming_pref));
1688     return;
1689 error:
1690     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1691 }
1692 
1693 static void requestCdmaSetRoamingPreference(int request __unused, void *data,
1694                                                  size_t datalen __unused, RIL_Token t)
1695 {
1696     int *pref = (int *)data;
1697     ATResponse *p_response = NULL;
1698     char *line;
1699     int res;
1700     char *cmd = NULL;
1701 
1702     asprintf(&cmd, "AT+WRMP=%d", *pref);
1703     if (cmd == NULL) goto error;
1704 
1705     res = at_send_command(cmd, &p_response);
1706     if (res < 0 || !p_response->success)
1707         goto error;
1708 
1709     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1710     free(cmd);
1711     return;
1712 error:
1713     free(cmd);
1714     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1715 }
1716 
1717 static int parseRegistrationState(char *str, int *type, int *items, int **response)
1718 {
1719     int err;
1720     char *line = str, *p;
1721     int *resp = NULL;
1722     int skip;
1723     int commas;
1724 
1725     s_lac = -1;
1726     s_cid = -1;
1727 
1728     RLOGD("parseRegistrationState. Parsing: %s",str);
1729     err = at_tok_start(&line);
1730     if (err < 0) goto error;
1731 
1732     /* Ok you have to be careful here
1733      * The solicited version of the CREG response is
1734      * +CREG: n, stat, [lac, cid]
1735      * and the unsolicited version is
1736      * +CREG: stat, [lac, cid]
1737      * The <n> parameter is basically "is unsolicited creg on?"
1738      * which it should always be
1739      *
1740      * Now we should normally get the solicited version here,
1741      * but the unsolicited version could have snuck in
1742      * so we have to handle both
1743      *
1744      * Also since the LAC and CID are only reported when registered,
1745      * we can have 1, 2, 3, or 4 arguments here
1746      *
1747      * finally, a +CGREG: answer may have a fifth value that corresponds
1748      * to the network type, as in;
1749      *
1750      *   +CGREG: n, stat [,lac, cid [,networkType]]
1751      */
1752 
1753     /* count number of commas */
1754     commas = 0;
1755     for (p = line ; *p != '\0' ;p++) {
1756         if (*p == ',') commas++;
1757     }
1758 
1759     resp = (int *)calloc(commas + 1, sizeof(int));
1760     if (!resp) goto error;
1761     switch (commas) {
1762         case 0: /* +CREG: <stat> */
1763             err = at_tok_nextint(&line, &resp[0]);
1764             if (err < 0) goto error;
1765             break;
1766 
1767         case 1: /* +CREG: <n>, <stat> */
1768             err = at_tok_nextint(&line, &skip);
1769             if (err < 0) goto error;
1770             err = at_tok_nextint(&line, &resp[0]);
1771             if (err < 0) goto error;
1772             break;
1773 
1774         case 2: /* +CREG: <stat>, <lac>, <cid> */
1775             err = at_tok_nextint(&line, &resp[0]);
1776             if (err < 0) goto error;
1777             err = at_tok_nexthexint(&line, &resp[1]);
1778             if (err < 0) goto error;
1779             err = at_tok_nexthexint(&line, &resp[2]);
1780             if (err < 0) goto error;
1781         break;
1782         case 3: /* +CREG: <n>, <stat>, <lac>, <cid> */
1783             err = at_tok_nextint(&line, &skip);
1784             if (err < 0) goto error;
1785             err = at_tok_nextint(&line, &resp[0]);
1786             if (err < 0) goto error;
1787             err = at_tok_nexthexint(&line, &resp[1]);
1788             if (err < 0) goto error;
1789             err = at_tok_nexthexint(&line, &resp[2]);
1790             if (err < 0) goto error;
1791         break;
1792         /* special case for CGREG, there is a fourth parameter
1793          * that is the network type (unknown/gprs/edge/umts)
1794          */
1795         case 4: /* +CGREG: <n>, <stat>, <lac>, <cid>, <networkType> */
1796             err = at_tok_nextint(&line, &skip);
1797             if (err < 0) goto error;
1798             err = at_tok_nextint(&line, &resp[0]);
1799             if (err < 0) goto error;
1800             err = at_tok_nexthexint(&line, &resp[1]);
1801             if (err < 0) goto error;
1802             err = at_tok_nexthexint(&line, &resp[2]);
1803             if (err < 0) goto error;
1804             err = at_tok_nextint(&line, &resp[3]);
1805             if (err < 0) goto error;
1806         break;
1807         default:
1808             goto error;
1809     }
1810 
1811     if (commas >= 2) {
1812         s_lac = resp[1];
1813         s_cid = resp[2];
1814     }
1815 
1816     if (response)
1817         *response = resp;
1818     if (items)
1819         *items = commas + 1;
1820     if (type)
1821         *type = techFromModemType(TECH(sMdmInfo));
1822     return 0;
1823 error:
1824     free(resp);
1825     return -1;
1826 }
1827 
1828 static int mapNetworkRegistrationResponse(int in_response) {
1829     int out_response = 0;
1830 
1831     switch (in_response) {
1832         case 0:
1833             out_response = RADIO_TECH_GPRS;    /* GPRS */
1834             break;
1835         case 3:
1836             out_response = RADIO_TECH_EDGE;    /* EDGE */
1837             break;
1838         case 2:
1839             out_response = RADIO_TECH_UMTS;    /* TD */
1840             break;
1841         case 4:
1842             out_response = RADIO_TECH_HSDPA;   /* HSDPA */
1843             break;
1844         case 5:
1845             out_response = RADIO_TECH_HSUPA;   /* HSUPA */
1846             break;
1847         case 6:
1848             out_response = RADIO_TECH_HSPA;    /* HSPA */
1849             break;
1850         case 15:
1851             out_response = RADIO_TECH_HSPAP;   /* HSPA+ */
1852             break;
1853         case 7:
1854             out_response = RADIO_TECH_LTE;     /* LTE */
1855             break;
1856         case 16:
1857             out_response = RADIO_TECH_LTE_CA;  /* LTE_CA */
1858             break;
1859         case 11:  // NR connected to a 5GCN
1860         case 12:  // NG-RAN
1861         case 13:  // E-UTRA-NR dual connectivity
1862             out_response = RADIO_TECH_NR;      /* NR */
1863             break;
1864         default:
1865             out_response = RADIO_TECH_UNKNOWN; /* UNKNOWN */
1866             break;
1867     }
1868     return out_response;
1869 }
1870 
1871 #define REG_STATE_LEN 18
1872 #define REG_DATA_STATE_LEN 14
1873 static void requestRegistrationState(int request, void *data __unused,
1874                                         size_t datalen __unused, RIL_Token t)
1875 {
1876     int err;
1877     int *registration;
1878     char **responseStr = NULL;
1879     ATResponse *p_response = NULL;
1880     const char *cmd;
1881     const char *prefix;
1882     char *line;
1883     int i = 0, j, numElements = 0;
1884     int count = 3;
1885     int type, startfrom;
1886 
1887     RLOGD("requestRegistrationState");
1888     if (request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
1889         cmd = "AT+CREG?";
1890         prefix = "+CREG:";
1891         numElements = REG_STATE_LEN;
1892     } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1893         cmd = "AT+CGREG?";
1894         prefix = "+CGREG:";
1895         numElements = REG_DATA_STATE_LEN;
1896         if (TECH_BIT(sMdmInfo) == MDM_LTE) {
1897             cmd = "AT+CEREG?";
1898             prefix = "+CEREG:";
1899         }
1900     } else {
1901         assert(0);
1902         goto error;
1903     }
1904 
1905     err = at_send_command_singleline(cmd, prefix, &p_response);
1906 
1907     if (err < 0 || !p_response->success) goto error;
1908 
1909     line = p_response->p_intermediates->line;
1910 
1911     if (parseRegistrationState(line, &type, &count, &registration)) goto error;
1912 
1913     responseStr = malloc(numElements * sizeof(char *));
1914     if (!responseStr) goto error;
1915     memset(responseStr, 0, numElements * sizeof(char *));
1916     /**
1917      * The first '4' bytes for both registration states remain the same.
1918      * But if the request is 'DATA_REGISTRATION_STATE',
1919      * the 5th and 6th byte(s) are optional.
1920      */
1921     if (is3gpp2(type) == 1) {
1922         RLOGD("registration state type: 3GPP2");
1923         // TODO: Query modem
1924         startfrom = 3;
1925         if(request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
1926             asprintf(&responseStr[3], "8");     // EvDo revA
1927             asprintf(&responseStr[4], "1");     // BSID
1928             asprintf(&responseStr[5], "123");   // Latitude
1929             asprintf(&responseStr[6], "222");   // Longitude
1930             asprintf(&responseStr[7], "0");     // CSS Indicator
1931             asprintf(&responseStr[8], "4");     // SID
1932             asprintf(&responseStr[9], "65535"); // NID
1933             asprintf(&responseStr[10], "0");    // Roaming indicator
1934             asprintf(&responseStr[11], "1");    // System is in PRL
1935             asprintf(&responseStr[12], "0");    // Default Roaming indicator
1936             asprintf(&responseStr[13], "0");    // Reason for denial
1937             asprintf(&responseStr[14], "0");    // Primary Scrambling Code of Current cell
1938       } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1939             asprintf(&responseStr[3], "8");   // Available data radio technology
1940       }
1941     } else { // type == RADIO_TECH_3GPP
1942         RLOGD("registration state type: 3GPP");
1943         startfrom = 0;
1944         if (count > 1) {
1945             asprintf(&responseStr[1], "%x", registration[1]);
1946         }
1947         if (count > 2) {
1948             asprintf(&responseStr[2], "%x", registration[2]);
1949         }
1950         if (count > 3) {
1951             asprintf(&responseStr[3], "%d", mapNetworkRegistrationResponse(registration[3]));
1952         }
1953     }
1954     asprintf(&responseStr[0], "%d", registration[0]);
1955 
1956     /**
1957      * Optional bytes for DATA_REGISTRATION_STATE request
1958      * 4th byte : Registration denial code
1959      * 5th byte : The max. number of simultaneous Data Calls
1960      */
1961     if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1962         // asprintf(&responseStr[4], "3");
1963         // asprintf(&responseStr[5], "1");
1964         asprintf(&responseStr[11], "%d", s_mcc);
1965         asprintf(&responseStr[12], "%d", s_mnc);
1966         if (s_mncLength == 2) {
1967           asprintf(&responseStr[13], "%03d%02d", s_mcc, s_mnc);
1968         } else {
1969           asprintf(&responseStr[13], "%03d%03d", s_mcc, s_mnc);
1970         }
1971     } else {  // Voice
1972         asprintf(&responseStr[15], "%d", s_mcc);
1973         asprintf(&responseStr[16], "%d", s_mnc);
1974         if (s_mncLength == 2) {
1975           asprintf(&responseStr[17], "%03d%02d", s_mcc, s_mnc);
1976         } else {
1977           asprintf(&responseStr[17], "%03d%03d", s_mcc, s_mnc);
1978         }
1979     }
1980 
1981 
1982     for (j = startfrom; j < numElements; j++) {
1983         if (!responseStr[i]) goto error;
1984     }
1985     free(registration);
1986     registration = NULL;
1987     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, numElements*sizeof(responseStr));
1988     for (j = 0; j < numElements; j++ ) {
1989         free(responseStr[j]);
1990         responseStr[j] = NULL;
1991     }
1992     free(responseStr);
1993     responseStr = NULL;
1994     at_response_free(p_response);
1995 
1996     return;
1997 error:
1998     if (responseStr) {
1999         for (j = 0; j < numElements; j++) {
2000             free(responseStr[j]);
2001             responseStr[j] = NULL;
2002         }
2003         free(responseStr);
2004         responseStr = NULL;
2005     }
2006     RLOGE("requestRegistrationState must never return an error when radio is on");
2007     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2008     at_response_free(p_response);
2009 }
2010 
2011 static void requestOperator(void *data __unused, size_t datalen __unused, RIL_Token t)
2012 {
2013     int err;
2014     int i;
2015     int skip;
2016     ATLine *p_cur;
2017     char *response[3];
2018 
2019     memset(response, 0, sizeof(response));
2020 
2021     ATResponse *p_response = NULL;
2022 
2023     err = at_send_command_multiline(
2024         "AT+COPS=3,0;+COPS?;+COPS=3,1;+COPS?;+COPS=3,2;+COPS?",
2025         "+COPS:", &p_response);
2026 
2027     /* we expect 3 lines here:
2028      * +COPS: 0,0,"T - Mobile"
2029      * +COPS: 0,1,"TMO"
2030      * +COPS: 0,2,"310170"
2031      */
2032 
2033     if (err != 0) goto error;
2034 
2035     for (i = 0, p_cur = p_response->p_intermediates
2036             ; p_cur != NULL
2037             ; p_cur = p_cur->p_next, i++
2038     ) {
2039         char *line = p_cur->line;
2040 
2041         err = at_tok_start(&line);
2042         if (err < 0) goto error;
2043 
2044         err = at_tok_nextint(&line, &skip);
2045         if (err < 0) goto error;
2046 
2047         // If we're unregistered, we may just get
2048         // a "+COPS: 0" response
2049         if (!at_tok_hasmore(&line)) {
2050             response[i] = NULL;
2051             continue;
2052         }
2053 
2054         err = at_tok_nextint(&line, &skip);
2055         if (err < 0) goto error;
2056 
2057         // a "+COPS: 0, n" response is also possible
2058         if (!at_tok_hasmore(&line)) {
2059             response[i] = NULL;
2060             continue;
2061         }
2062 
2063         err = at_tok_nextstr(&line, &(response[i]));
2064         if (err < 0) goto error;
2065         // Simple assumption that mcc and mnc are 3 digits each
2066         int length = strlen(response[i]);
2067         if (length == 6) {
2068             s_mncLength = 3;
2069             if (sscanf(response[i], "%3d%3d", &s_mcc, &s_mnc) != 2) {
2070                 RLOGE("requestOperator expected mccmnc to be 6 decimal digits");
2071             }
2072         } else if (length == 5) {
2073             s_mncLength = 2;
2074             if (sscanf(response[i], "%3d%2d", &s_mcc, &s_mnc) != 2) {
2075                 RLOGE("requestOperator expected mccmnc to be 5 decimal digits");
2076             }
2077         }
2078     }
2079 
2080     if (i != 3) {
2081         /* expect 3 lines exactly */
2082         goto error;
2083     }
2084 
2085     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
2086     at_response_free(p_response);
2087 
2088     return;
2089 error:
2090     RLOGE("requestOperator must not return error when radio is on");
2091     s_mncLength = 0;
2092     s_mcc = 0;
2093     s_mnc = 0;
2094     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2095     at_response_free(p_response);
2096 }
2097 
2098 static void requestCdmaSendSMS(void *data, size_t datalen, RIL_Token t)
2099 {
2100     int err = 1; // Set to go to error:
2101     RIL_SMS_Response response;
2102     RIL_CDMA_SMS_Message* rcsm;
2103 
2104     memset(&response, 0, sizeof(response));
2105 
2106     if (getSIMStatus() == SIM_ABSENT) {
2107         RIL_onRequestComplete(t, RIL_E_SIM_ABSENT, NULL, 0);
2108         return;
2109     }
2110 
2111     RLOGD("requestCdmaSendSMS datalen=%zu, sizeof(RIL_CDMA_SMS_Message)=%zu",
2112             datalen, sizeof(RIL_CDMA_SMS_Message));
2113 
2114     // verify data content to test marshalling/unmarshalling:
2115     rcsm = (RIL_CDMA_SMS_Message*)data;
2116     RLOGD("TeleserviceID=%d, bIsServicePresent=%d, \
2117             uServicecategory=%d, sAddress.digit_mode=%d, \
2118             sAddress.Number_mode=%d, sAddress.number_type=%d, ",
2119             rcsm->uTeleserviceID,  rcsm->bIsServicePresent,
2120             rcsm->uServicecategory,rcsm->sAddress.digit_mode,
2121             rcsm->sAddress.number_mode,rcsm->sAddress.number_type);
2122 
2123     if (err != 0) goto error;
2124 
2125     // Cdma Send SMS implementation will go here:
2126     // But it is not implemented yet.
2127 
2128     response.messageRef = 1;
2129     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
2130     return;
2131 
2132 error:
2133     // Cdma Send SMS will always cause send retry error.
2134     response.messageRef = -1;
2135     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
2136 }
2137 
2138 static void requestSendSMS(void *data, size_t datalen, RIL_Token t)
2139 {
2140     int err;
2141     const char *smsc;
2142     const char *pdu;
2143     int tpLayerLength;
2144     char *cmd1, *cmd2;
2145     RIL_SMS_Response response;
2146     ATResponse *p_response = NULL;
2147 
2148     if (getSIMStatus() == SIM_ABSENT) {
2149         RIL_onRequestComplete(t, RIL_E_SIM_ABSENT, NULL, 0);
2150         return;
2151     }
2152 
2153     memset(&response, 0, sizeof(response));
2154     RLOGD("requestSendSMS datalen =%zu", datalen);
2155 
2156     if (s_ims_gsm_fail != 0) goto error;
2157     if (s_ims_gsm_retry != 0) goto error2;
2158 
2159     smsc = ((const char **)data)[0];
2160     pdu = ((const char **)data)[1];
2161 
2162     tpLayerLength = strlen(pdu)/2;
2163 
2164     // "NULL for default SMSC"
2165     if (smsc == NULL) {
2166         smsc= "00";
2167     }
2168 
2169     asprintf(&cmd1, "AT+CMGS=%d", tpLayerLength);
2170     asprintf(&cmd2, "%s%s", smsc, pdu);
2171 
2172     err = at_send_command_sms(cmd1, cmd2, "+CMGS:", &p_response);
2173 
2174     free(cmd1);
2175     free(cmd2);
2176 
2177     if (err != 0 || p_response->success == 0) goto error;
2178 
2179     int messageRef = 1;
2180     char *line = p_response->p_intermediates->line;
2181 
2182     err = at_tok_start(&line);
2183     if (err < 0) goto error;
2184 
2185     err = at_tok_nextint(&line, &messageRef);
2186     if (err < 0) goto error;
2187 
2188     /* FIXME fill in ackPDU */
2189     response.messageRef = messageRef;
2190     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
2191     at_response_free(p_response);
2192 
2193     return;
2194 error:
2195     response.messageRef = -2;
2196     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, &response, sizeof(response));
2197     at_response_free(p_response);
2198     return;
2199 error2:
2200     // send retry error.
2201     response.messageRef = -1;
2202     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
2203     at_response_free(p_response);
2204     return;
2205 }
2206 
2207 static void requestImsSendSMS(void *data, size_t datalen, RIL_Token t)
2208 {
2209     RIL_IMS_SMS_Message *p_args;
2210     RIL_SMS_Response response;
2211 
2212     memset(&response, 0, sizeof(response));
2213 
2214     RLOGD("requestImsSendSMS: datalen=%zu, "
2215         "registered=%d, service=%d, format=%d, ims_perm_fail=%d, "
2216         "ims_retry=%d, gsm_fail=%d, gsm_retry=%d",
2217         datalen, s_ims_registered, s_ims_services, s_ims_format,
2218         s_ims_cause_perm_failure, s_ims_cause_retry, s_ims_gsm_fail,
2219         s_ims_gsm_retry);
2220 
2221     // figure out if this is gsm/cdma format
2222     // then route it to requestSendSMS vs requestCdmaSendSMS respectively
2223     p_args = (RIL_IMS_SMS_Message *)data;
2224 
2225     if (0 != s_ims_cause_perm_failure ) goto error;
2226 
2227     // want to fail over ims and this is first request over ims
2228     if (0 != s_ims_cause_retry && 0 == p_args->retry) goto error2;
2229 
2230     if (RADIO_TECH_3GPP == p_args->tech) {
2231         return requestSendSMS(p_args->message.gsmMessage,
2232                 datalen - sizeof(RIL_RadioTechnologyFamily),
2233                 t);
2234     } else if (RADIO_TECH_3GPP2 == p_args->tech) {
2235         return requestCdmaSendSMS(p_args->message.cdmaMessage,
2236                 datalen - sizeof(RIL_RadioTechnologyFamily),
2237                 t);
2238     } else {
2239         RLOGE("requestImsSendSMS invalid format value =%d", p_args->tech);
2240     }
2241 
2242 error:
2243     response.messageRef = -2;
2244     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, &response, sizeof(response));
2245     return;
2246 
2247 error2:
2248     response.messageRef = -1;
2249     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
2250 }
2251 
2252 /**
2253  * Add for CTS test
2254  * If open logical channel with AID NULL, this means open logical channel to MF.
2255  * If there is P2 value, this P2 value is used for SELECT command.
2256  * In addition, if SELECT command returns 61xx, GET RESPONSE command needs to send to get data.
2257  */
2258 static int sendCmdAgainForOpenChannelWithP2( char *data,
2259                                         int p2, int *response, int *rspLen) {
2260     int len = 0;
2261     int err = -1;
2262     char *line = NULL;
2263     char cmd[64] = {0};
2264     RIL_Errno errType = RIL_E_GENERIC_FAILURE;
2265     ATResponse *p_response = NULL;
2266     RIL_SIM_IO_Response sr;
2267 
2268     memset(&sr, 0, sizeof(sr));
2269     sscanf(data, "%2x", &(response[0]));  // response[0] is channel number
2270 
2271     // Send SELECT command to MF
2272     snprintf(cmd, sizeof(cmd), "AT+CGLA=%d,14,00A400%02X023F00", response[0],
2273              p2);
2274 
2275     err = at_send_command_singleline(cmd, "+CGLA:", &p_response);
2276     if (err < 0) goto done;
2277     if (p_response->success == 0) {
2278         if (!strcmp(p_response->finalResponse, "+CME ERROR: 21") ||
2279             !strcmp(p_response->finalResponse, "+CME ERROR: 50")) {
2280             errType = RIL_E_GENERIC_FAILURE;
2281         }
2282         goto done;
2283     }
2284 
2285     line = p_response->p_intermediates->line;
2286 
2287     if (at_tok_start(&line) < 0 || at_tok_nextint(&line, &len) < 0 ||
2288         at_tok_nextstr(&line, &(sr.simResponse)) < 0) {
2289         goto done;
2290     }
2291 
2292     sscanf(&(sr.simResponse[len - 4]), "%02x%02x", &(sr.sw1), &(sr.sw2));
2293 
2294     if (sr.sw1 == 0x90 && sr.sw2 == 0x00) {  // 9000 is successful
2295         int length = len / 2;
2296         for (*rspLen = 1; *rspLen <= length; (*rspLen)++) {
2297             sscanf(sr.simResponse, "%02x", &(response[*rspLen]));
2298             sr.simResponse += 2;
2299         }
2300         errType = RIL_E_SUCCESS;
2301     } else {  // close channel
2302         snprintf(cmd, sizeof(cmd), "AT+CCHC=%d", response[0]);
2303         at_send_command( cmd, NULL);
2304     }
2305 
2306 done:
2307     at_response_free(p_response);
2308     return errType;
2309 }
2310 
2311 static void requestSimOpenChannel(void *data, size_t datalen, RIL_Token t)
2312 {
2313     RIL_UNUSED_PARM(datalen);
2314 
2315     ATResponse *p_response = NULL;
2316     int response[260] = {0};
2317     int responseLen = 1;
2318     int32_t session_id;
2319     int err;
2320     char cmd[64] = {0};
2321     char complex;
2322     char *line = NULL;
2323     int skip = 0;
2324     char *statusWord = NULL;
2325     int err_no = RIL_E_GENERIC_FAILURE;
2326 
2327     RIL_OpenChannelParams *params = (RIL_OpenChannelParams *)data;
2328 
2329     // Max length is 16 bytes according to 3GPP spec 27.007 section 8.45
2330     if (params->aidPtr == NULL) {
2331           err = at_send_command_singleline("AT+CSIM=10,\"0070000001\"", "+CSIM:", &p_response);
2332     } else {
2333         snprintf(cmd, sizeof(cmd), "AT+CCHO=%s", params->aidPtr);
2334         err = at_send_command_numeric(cmd, &p_response);
2335     }
2336 
2337     if (err < 0 || p_response == NULL || p_response->success == 0) {
2338         ALOGE("Error %d opening logical channel: %d",
2339               err, p_response ? p_response->success : 0);
2340         goto error;
2341     }
2342 
2343     // Ensure integer only by scanning for an extra char but expect one result
2344     line = p_response->p_intermediates->line;
2345     if (params->aidPtr == NULL) {
2346 
2347         err = at_tok_start(&line);
2348         if (err < 0) goto error;
2349 
2350         err = at_tok_nextint(&line, &skip);
2351         if (err < 0) goto error;
2352 
2353         err = at_tok_nextstr(&line, &statusWord);
2354         if (err < 0) goto error;
2355 
2356         if (params->p2 < 0) {
2357             int length = strlen(statusWord) / 2;
2358             for (responseLen = 0; responseLen < length; responseLen++) {
2359                 sscanf(statusWord, "%02x", &(response[responseLen]));
2360                 statusWord += 2;
2361             }
2362             err_no = RIL_E_SUCCESS;
2363         } else {
2364             response[0] = 1;
2365             err_no = sendCmdAgainForOpenChannelWithP2(statusWord,
2366                                         params->p2, response, &responseLen);
2367             if (err_no != RIL_E_SUCCESS) {
2368                 goto error;
2369             }
2370         }
2371         RIL_onRequestComplete(t, err_no, response, responseLen * sizeof(int));
2372         at_response_free(p_response);
2373         return;
2374     } else {
2375         if (sscanf(line, "%" SCNd32 "%c", &session_id, &complex) != 1) {
2376            ALOGE("Invalid AT response, expected integer, was '%s'", line);
2377            goto error;
2378         }
2379     }
2380 
2381     RIL_onRequestComplete(t, RIL_E_SUCCESS, &session_id, sizeof(session_id));
2382     at_response_free(p_response);
2383     return;
2384 
2385 error:
2386     RIL_onRequestComplete(t, err_no, NULL, 0);
2387     at_response_free(p_response);
2388     return;
2389 }
2390 
2391 static void requestSimCloseChannel(void *data, size_t datalen, RIL_Token t)
2392 {
2393     ATResponse *p_response = NULL;
2394     int32_t session_id;
2395     int err;
2396     char cmd[32];
2397 
2398     if (data == NULL || datalen != sizeof(session_id)) {
2399         ALOGE("Invalid data passed to requestSimCloseChannel");
2400         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2401         return;
2402     }
2403     session_id = ((int32_t *)data)[0];
2404     if (session_id == 0) {
2405         RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
2406         return;
2407     }
2408 
2409     snprintf(cmd, sizeof(cmd), "AT+CCHC=%" PRId32, session_id);
2410     err = at_send_command_singleline(cmd, "+CCHC", &p_response);
2411 
2412     if (err < 0 || p_response == NULL || p_response->success == 0) {
2413         ALOGE("Error %d closing logical channel %d: %d",
2414               err, session_id, p_response ? p_response->success : 0);
2415         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2416         at_response_free(p_response);
2417         return;
2418     }
2419 
2420     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2421 
2422     at_response_free(p_response);
2423 }
2424 
2425 static void requestSimTransmitApduChannel(void *data,
2426                                           size_t datalen,
2427                                           RIL_Token t)
2428 {
2429     ATResponse *p_response = NULL;
2430     int err;
2431     int len = 0;
2432     char *cmd;
2433     char *line = NULL;
2434     size_t cmd_size;
2435     RIL_SIM_IO_Response sr = {0};
2436     RIL_SIM_APDU *apdu = (RIL_SIM_APDU *)data;
2437 
2438     if (apdu == NULL || datalen != sizeof(RIL_SIM_APDU)) {
2439         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2440         return;
2441     }
2442 
2443     cmd_size = 10 + (apdu->data ? strlen(apdu->data) : 0);
2444     asprintf(&cmd, "AT+CGLA=%d,%zu,%02x%02x%02x%02x%02x%s",
2445              apdu->sessionid, cmd_size, apdu->cla, apdu->instruction,
2446              apdu->p1, apdu->p2, apdu->p3, apdu->data ? apdu->data : "");
2447 
2448     err = at_send_command_singleline(cmd, "+CGLA:", &p_response);
2449     free(cmd);
2450     if (err < 0 || p_response == NULL || p_response->success == 0) {
2451         ALOGE("Error %d transmitting APDU: %d",
2452               err, p_response ? p_response->success : 0);
2453         goto error;
2454     }
2455 
2456     line = p_response->p_intermediates->line;
2457     err = at_tok_start(&line);
2458     if (err < 0) goto error;
2459 
2460     err = at_tok_nextint(&line, &len);
2461     if (err < 0) goto error;
2462 
2463     err = at_tok_nextstr(&line, &(sr.simResponse));
2464     if (err < 0) goto error;
2465 
2466     len = strlen(sr.simResponse);
2467     if (len < 4) goto error;
2468 
2469     sscanf(&(sr.simResponse[len - 4]), "%02x%02x", &(sr.sw1), &(sr.sw2));
2470     sr.simResponse[len - 4] = '\0';
2471 
2472     RIL_onRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
2473     at_response_free(p_response);
2474     return;
2475 
2476 error:
2477     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2478     at_response_free(p_response);
2479 }
2480 
2481 static void requestSimAuthentication(int authContext, char* authData, RIL_Token t) {
2482     int err = -1, ret = 0;
2483     int status = 0;
2484     int binSimResponseLen = 0;
2485     char *cmd = NULL;
2486     char *line = NULL;
2487     // Input data
2488     int randLen = 0, autnLen = 0;
2489     char *rand = NULL, *autn = NULL;
2490     // EAP-SIM response data
2491     int kcLen = 0, sresLen = 0;
2492     char *kc = NULL, *sres = NULL;
2493     // EAP-AKA response data
2494     int ckLen = 0, ikLen = 0, resAutsLen = 0;
2495     char *ck = NULL, *ik = NULL, *resAuts = NULL;
2496     unsigned char *binSimResponse = NULL;
2497     unsigned char *binAuthData = NULL;
2498     unsigned char *hexAuthData = NULL;
2499     ATResponse *p_response = NULL;
2500     RIL_SIM_IO_Response response;
2501 
2502     memset(&response, 0, sizeof(response));
2503     response.sw1 = 0x90;
2504     response.sw2 = 0;
2505 
2506     binAuthData  =
2507             (unsigned char *)malloc(sizeof(*binAuthData) * strlen(authData));
2508     if (binAuthData == NULL) {
2509         goto error;
2510     }
2511     if(base64_decode(authData, binAuthData) <= 0) {
2512         RLOGE("base64_decode failed %s %d", __func__, __LINE__);
2513         goto error;
2514     }
2515     hexAuthData =
2516             (unsigned char *)malloc(strlen(authData) * 2 + sizeof(char));
2517     if (hexAuthData == NULL) {
2518         goto error;
2519     }
2520     memset(hexAuthData, 0, strlen(authData) * 2 + sizeof(char));
2521     convertBytesToHexString((char *)binAuthData, strlen(authData), hexAuthData);
2522 
2523     randLen = binAuthData[0];
2524     rand = (char *)malloc(sizeof(char) * (randLen * 2 + sizeof(char)));
2525     if (rand == NULL) {
2526         goto error;
2527     }
2528     memcpy(rand, hexAuthData + 2, randLen * 2);
2529     memcpy(rand + randLen * 2, "\0", 1);
2530 
2531     if (authContext == AUTH_CONTEXT_EAP_AKA) {
2532         // There's the autn value to parse as well.
2533         autnLen = binAuthData[1 + randLen];
2534         autn = (char*)malloc(sizeof(char) * (autnLen * 2 + sizeof(char)));
2535         if (autn == NULL) {
2536             goto error;
2537         }
2538         memcpy(autn, hexAuthData + 2 + randLen * 2 + 2, autnLen * 2);
2539         memcpy(autn + autnLen * 2, "\0", 1);
2540     }
2541 
2542     if (authContext == AUTH_CONTEXT_EAP_SIM) {
2543         ret = asprintf(&cmd, "AT^MBAU=\"%s\"", rand);
2544     } else {
2545         ret = asprintf(&cmd, "AT^MBAU=\"%s,%s\"", rand, autn);
2546     }
2547     if (ret < 0) {
2548         RLOGE("Failed to asprintf");
2549         goto error;
2550     }
2551     err = at_send_command_singleline( cmd, "^MBAU:", &p_response);
2552     free(cmd);
2553 
2554     if (err < 0 || p_response->success == 0) {
2555         goto error;
2556     }
2557     line = p_response->p_intermediates->line;
2558     err = at_tok_start(&line);
2559     if (err < 0) goto error;
2560 
2561     err = at_tok_nextint(&line, &status);
2562     if (err < 0) goto error;
2563     if (status != SIM_AUTH_RESPONSE_SUCCESS) {
2564         goto error;
2565     }
2566 
2567     if (authContext == AUTH_CONTEXT_EAP_SIM) {
2568         err = at_tok_nextstr(&line, &kc);
2569         if (err < 0) goto error;
2570         kcLen = strlen(kc);
2571 
2572         err = at_tok_nextstr(&line, &sres);
2573         if (err < 0) goto error;
2574         sresLen = strlen(sres);
2575 
2576         // sresLen + sres + kcLen + kc + '\0'
2577         binSimResponseLen = (kcLen + sresLen) / 2 + 3 * sizeof(char);
2578         binSimResponse = (unsigned char*)malloc(binSimResponseLen + sizeof(char));
2579         if (binSimResponse == NULL) goto error;
2580         memset(binSimResponse, 0, binSimResponseLen);
2581         // set sresLen and sres
2582         binSimResponse[0] = (sresLen / 2) & 0xFF;
2583         uint8_t* tmpBinSimResponse = convertHexStringToBytes(sres, sresLen);
2584         snprintf((char*)(binSimResponse + 1), sresLen / 2, "%s", tmpBinSimResponse);
2585         free(tmpBinSimResponse);
2586         tmpBinSimResponse = NULL;
2587         // set kcLen and kc
2588         binSimResponse[1 + sresLen / 2] = (kcLen / 2) & 0xFF;
2589         tmpBinSimResponse = convertHexStringToBytes(kc, kcLen);
2590         snprintf((char*)(binSimResponse + 1 + sresLen / 2 + 1), kcLen / 2, "%s", tmpBinSimResponse);
2591         free(tmpBinSimResponse);
2592         tmpBinSimResponse = NULL;
2593     } else {  // AUTH_CONTEXT_EAP_AKA
2594         err = at_tok_nextstr(&line, &ck);
2595         if (err < 0) goto error;
2596         ckLen = strlen(ck);
2597 
2598         err = at_tok_nextstr(&line, &ik);
2599         if (err < 0) goto error;
2600         ikLen = strlen(ik);
2601 
2602         err = at_tok_nextstr(&line, &resAuts);
2603         if (err < 0) goto error;
2604         resAutsLen = strlen(resAuts);
2605 
2606         // 0xDB + ckLen + ck + ikLen + ik + resAutsLen + resAuts + '\0'
2607         binSimResponseLen = (ckLen + ikLen + resAutsLen) / 2 + 5 * sizeof(char);
2608         binSimResponse = (unsigned char*)malloc(binSimResponseLen + sizeof(char));
2609         if (binSimResponse == NULL) goto error;
2610         memset(binSimResponse, 0, binSimResponseLen);
2611         // The DB prefix indicates successful auth. Not produced by the SIM.
2612         binSimResponse[0] = 0xDB;
2613         // Set ckLen and ck
2614         binSimResponse[1] = (ckLen / 2) & 0xFF;
2615         uint8_t* tmpBinSimResponse = convertHexStringToBytes(ck, ckLen);
2616         snprintf((char*)(binSimResponse + 2), ckLen / 2 + 1, "%s", tmpBinSimResponse);
2617         free(tmpBinSimResponse);
2618         tmpBinSimResponse = NULL;
2619         // Set ikLen and ik
2620         binSimResponse[2 + ckLen / 2] = (ikLen / 2) & 0xFF;
2621         tmpBinSimResponse = convertHexStringToBytes(ik, ikLen);
2622         snprintf((char*)(binSimResponse + 2 + ckLen / 2 + 1), ikLen / 2 + 1, "%s",
2623                  tmpBinSimResponse);
2624         free(tmpBinSimResponse);
2625         tmpBinSimResponse = NULL;
2626         // Set resAutsLen and resAuts
2627         binSimResponse[2 + ckLen / 2 + 1 + ikLen / 2] = (resAutsLen / 2) & 0xFF;
2628         tmpBinSimResponse = convertHexStringToBytes(resAuts, resAutsLen);
2629         snprintf((char*)(binSimResponse + 2 + ckLen / 2 + 1 + ikLen / 2 + 1), resAutsLen / 2 + 1,
2630                  "%s", tmpBinSimResponse);
2631         free(tmpBinSimResponse);
2632         tmpBinSimResponse = NULL;
2633     }
2634 
2635     response.simResponse = (char*)malloc(2 * binSimResponseLen + sizeof(char));
2636     if (response.simResponse == NULL) goto error;
2637     if (NULL == base64_encode(binSimResponse, response.simResponse, binSimResponseLen - 1)) {
2638         RLOGE("Failed to call base64_encode %s %d", __func__, __LINE__);
2639         goto error;
2640     }
2641 
2642     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
2643     at_response_free(p_response);
2644 
2645     free(binAuthData);
2646     free(hexAuthData);
2647     free(rand);
2648     free(autn);
2649     free(response.simResponse);
2650     free(binSimResponse);
2651     return;
2652 
2653 error:
2654     free(binAuthData);
2655     free(hexAuthData);
2656     free(rand);
2657     free(autn);
2658     free(response.simResponse);
2659     free(binSimResponse);
2660 
2661     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2662     at_response_free(p_response);
2663 }
2664 
2665 static void requestTransmitApduBasic( void *data, size_t datalen,
2666                                       RIL_Token t) {
2667     RIL_UNUSED_PARM(datalen);
2668 
2669     int err, len;
2670     char *cmd = NULL;
2671     char *line = NULL;
2672     RIL_SIM_APDU *p_args = NULL;
2673     ATResponse *p_response = NULL;
2674     RIL_SIM_IO_Response sr;
2675 
2676     memset(&sr, 0, sizeof(sr));
2677 
2678     p_args = (RIL_SIM_APDU *)data;
2679 
2680     if ((p_args->data == NULL) || (strlen(p_args->data) == 0)) {
2681         if (p_args->p3 < 0) {
2682             asprintf(&cmd, "AT+CSIM=%d,\"%02x%02x%02x%02x\"", 8, p_args->cla,
2683                     p_args->instruction, p_args->p1, p_args->p2);
2684         } else {
2685             asprintf(&cmd, "AT+CSIM=%d,\"%02x%02x%02x%02x%02x\"", 10,
2686                     p_args->cla, p_args->instruction, p_args->p1, p_args->p2,
2687                     p_args->p3);
2688         }
2689     } else {
2690         asprintf(&cmd, "AT+CSIM=%d,\"%02x%02x%02x%02x%02x%s\"",
2691                 10 + (int)strlen(p_args->data), p_args->cla,
2692                 p_args->instruction, p_args->p1, p_args->p2, p_args->p3,
2693                 p_args->data);
2694     }
2695     err = at_send_command_singleline(cmd, "+CSIM:", &p_response);
2696     free(cmd);
2697     if (err < 0 || p_response->success == 0) {
2698         goto error;
2699     }
2700 
2701     line = p_response->p_intermediates->line;
2702     err = at_tok_start(&line);
2703     if (err < 0) goto error;
2704 
2705     err = at_tok_nextint(&line, &len);
2706     if (err < 0) goto error;
2707 
2708     err = at_tok_nextstr(&line, &(sr.simResponse));
2709     if (err < 0) goto error;
2710 
2711     sscanf(&(sr.simResponse[len - 4]), "%02x%02x", &(sr.sw1), &(sr.sw2));
2712     sr.simResponse[len - 4] = '\0';
2713 
2714     RIL_onRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
2715     at_response_free(p_response);
2716     return;
2717 
2718 error:
2719     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2720     at_response_free(p_response);
2721 }
2722 
2723 static int getPDP() {
2724     int ret = -1;
2725 
2726     for (int i = 0; i < MAX_PDP; i++) {
2727         if (s_PDP[i].state == PDP_IDLE) {
2728             s_PDP[i].state = PDP_BUSY;
2729             ret = s_PDP[i].cid;
2730             break;
2731         }
2732     }
2733     return ret;
2734 }
2735 
2736 static void putPDP(int cid) {
2737     if (cid < 1 || cid > MAX_PDP ) {
2738         return;
2739     }
2740 
2741     s_PDP[cid - 1].state = PDP_IDLE;
2742 }
2743 
2744 static void requestSetupDataCall(void *data, size_t datalen, RIL_Token t)
2745 {
2746     const char *apn = NULL;
2747     char *cmd = NULL;
2748     int err = -1;
2749     int cid = -1;
2750     ATResponse *p_response = NULL;
2751 
2752     apn = ((const char **)data)[2];
2753 
2754 #ifdef USE_TI_COMMANDS
2755     // Config for multislot class 10 (probably default anyway eh?)
2756     err = at_send_command("AT%CPRIM=\"GMM\",\"CONFIG MULTISLOT_CLASS=<10>\"",
2757                         NULL);
2758 
2759     err = at_send_command("AT%DATA=2,\"UART\",1,,\"SER\",\"UART\",0", NULL);
2760 #endif /* USE_TI_COMMANDS */
2761 
2762     int fd, qmistatus;
2763     size_t cur = 0;
2764     size_t len;
2765     ssize_t written, rlen;
2766     char status[32] = {0};
2767     int retry = 10;
2768     const char *pdp_type;
2769 
2770     RLOGD("requesting data connection to APN '%s'", apn);
2771 
2772     fd = open ("/dev/qmi", O_RDWR);
2773     if (fd >= 0) { /* the device doesn't exist on the emulator */
2774 
2775         RLOGD("opened the qmi device\n");
2776         asprintf(&cmd, "up:%s", apn);
2777         len = strlen(cmd);
2778 
2779         while (cur < len) {
2780             do {
2781                 written = write (fd, cmd + cur, len - cur);
2782             } while (written < 0 && errno == EINTR);
2783 
2784             if (written < 0) {
2785                 RLOGE("### ERROR writing to /dev/qmi");
2786                 close(fd);
2787                 goto error;
2788             }
2789 
2790             cur += written;
2791         }
2792 
2793         // wait for interface to come online
2794 
2795         do {
2796             sleep(1);
2797             do {
2798                 rlen = read(fd, status, 31);
2799             } while (rlen < 0 && errno == EINTR);
2800 
2801             if (rlen < 0) {
2802                 RLOGE("### ERROR reading from /dev/qmi");
2803                 close(fd);
2804                 goto error;
2805             } else {
2806                 status[rlen] = '\0';
2807                 RLOGD("### status: %s", status);
2808             }
2809         } while (strncmp(status, "STATE=up", 8) && strcmp(status, "online") && --retry);
2810 
2811         close(fd);
2812 
2813         if (retry == 0) {
2814             RLOGE("### Failed to get data connection up\n");
2815             goto error;
2816         }
2817 
2818         qmistatus = system("netcfg buried_eth0 dhcp");
2819 
2820         RLOGD("netcfg buried_eth0 dhcp: status %d\n", qmistatus);
2821 
2822         if (qmistatus < 0) goto error;
2823 
2824     } else {
2825         const char* radioInterfaceName = getRadioInterfaceName();
2826         if (setInterfaceState(radioInterfaceName, kInterfaceUp) != RIL_E_SUCCESS) {
2827             goto error;
2828         }
2829 
2830         if (datalen > 6 * sizeof(char *)) {
2831             pdp_type = ((const char **)data)[6];
2832         } else {
2833             pdp_type = "IP";
2834         }
2835 
2836         cid = getPDP();
2837         if (cid < 1) {
2838             RLOGE("SETUP_DATA_CALL MAX_PDP reached.");
2839             RIL_Data_Call_Response_v11 response;
2840             response.status = 0x41 /* PDP_FAIL_MAX_ACTIVE_PDP_CONTEXT_REACHED */;
2841             response.suggestedRetryTime = -1;
2842             response.cid = cid;
2843             response.active = -1;
2844             response.type = "";
2845             response.ifname = "";
2846             response.addresses = "";
2847             response.dnses = "";
2848             response.gateways = "";
2849             response.pcscf = "";
2850             response.mtu = 0;
2851             RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(RIL_Data_Call_Response_v11));
2852             at_response_free(p_response);
2853             return;
2854         }
2855 
2856         asprintf(&cmd, "AT+CGDCONT=%d,\"%s\",\"%s\",,0,0", cid, pdp_type, apn);
2857         //FIXME check for error here
2858         err = at_send_command(cmd, NULL);
2859         free(cmd);
2860 
2861         // Set required QoS params to default
2862         err = at_send_command("AT+CGQREQ=1", NULL);
2863 
2864         // Set minimum QoS params to default
2865         err = at_send_command("AT+CGQMIN=1", NULL);
2866 
2867         // packet-domain event reporting
2868         err = at_send_command("AT+CGEREP=1,0", NULL);
2869 
2870         // Hangup anything that's happening there now
2871         err = at_send_command("AT+CGACT=1,0", NULL);
2872 
2873         // Start data on PDP context 1
2874         err = at_send_command("ATD*99***1#", &p_response);
2875 
2876         if (err < 0 || p_response->success == 0) {
2877             goto error;
2878         }
2879     }
2880 
2881     requestOrSendDataCallList(cid, &t);
2882 
2883     at_response_free(p_response);
2884 
2885     return;
2886 error:
2887     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2888     at_response_free(p_response);
2889 }
2890 
2891 static void requestDeactivateDataCall(void *data, RIL_Token t)
2892 {
2893     const char *p_cid = ((const char **)data)[0];
2894     int cid = p_cid ? atoi(p_cid) : -1;
2895     RIL_Errno rilErrno = RIL_E_GENERIC_FAILURE;
2896     if (cid < 1  || cid > MAX_PDP) {
2897         RIL_onRequestComplete(t, rilErrno, NULL, 0);
2898         return;
2899     }
2900 
2901     const char* radioInterfaceName = getRadioInterfaceName();
2902     rilErrno = setInterfaceState(radioInterfaceName, kInterfaceDown);
2903     RIL_onRequestComplete(t, rilErrno, NULL, 0);
2904     putPDP(cid);
2905     requestOrSendDataCallList(-1, NULL);
2906 }
2907 
2908 static void requestSMSAcknowledge(void *data, size_t datalen __unused, RIL_Token t)
2909 {
2910     int ackSuccess;
2911     int err;
2912 
2913     if (getSIMStatus() == SIM_ABSENT) {
2914         RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
2915         return;
2916     }
2917 
2918     ackSuccess = ((int *)data)[0];
2919 
2920     if (ackSuccess == 1) {
2921         err = at_send_command("AT+CNMA=1", NULL);
2922         if (err < 0) {
2923             goto error;
2924         }
2925     } else if (ackSuccess == 0)  {
2926         err = at_send_command("AT+CNMA=2", NULL);
2927         if (err < 0) {
2928             goto error;
2929         }
2930     } else {
2931         RLOGE("unsupported arg to RIL_REQUEST_SMS_ACKNOWLEDGE\n");
2932         goto error;
2933     }
2934 
2935     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2936 
2937     return;
2938 error:
2939     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2940 }
2941 
2942 void convertBytesToHex(uint8_t *bytes, int length, uint8_t *hex_str) {
2943     int i;
2944     unsigned char tmp;
2945 
2946     if (bytes == NULL || hex_str == NULL) {
2947         return;
2948     }
2949     for (i = 0; i < length; i++) {
2950         tmp = (unsigned char)((bytes[i] & 0xf0) >> 4);
2951         if (tmp <= 9) {
2952             *hex_str = (unsigned char)(tmp + '0');
2953         } else {
2954             *hex_str = (unsigned char)(tmp + 'A' - 10);
2955         }
2956         hex_str++;
2957         tmp = (unsigned char)(bytes[i] & 0x0f);
2958         if (tmp <= 9) {
2959             *hex_str = (unsigned char)(tmp + '0');
2960         } else {
2961             *hex_str = (unsigned char)(tmp + 'A' - 10);
2962         }
2963         hex_str++;
2964     }
2965 }
2966 
2967 #define TYPE_EF                                 4
2968 #define RESPONSE_EF_SIZE                        15
2969 #define TYPE_FILE_DES_LEN                       5
2970 #define RESPONSE_DATA_FILE_DES_FLAG             2
2971 #define RESPONSE_DATA_FILE_DES_LEN_FLAG         3
2972 #define RESPONSE_DATA_FILE_TYPE                 6
2973 #define RESPONSE_DATA_FILE_SIZE_1               2
2974 #define RESPONSE_DATA_FILE_SIZE_2               3
2975 #define RESPONSE_DATA_STRUCTURE                 13
2976 #define RESPONSE_DATA_RECORD_LENGTH             14
2977 #define RESPONSE_DATA_FILE_RECORD_LEN_1         6
2978 #define RESPONSE_DATA_FILE_RECORD_LEN_2         7
2979 #define EF_TYPE_TRANSPARENT                     0x01
2980 #define EF_TYPE_LINEAR_FIXED                    0x02
2981 #define EF_TYPE_CYCLIC                          0x06
2982 #define USIM_DATA_OFFSET_2                      2
2983 #define USIM_DATA_OFFSET_3                      3
2984 #define USIM_FILE_DES_TAG                       0x82
2985 #define USIM_FILE_SIZE_TAG                      0x80
2986 
2987 bool convertUsimToSim(uint8_t *byteUSIM, int len, uint8_t *hexSIM) {
2988     int desIndex = 0;
2989     int sizeIndex = 0;
2990     int i = 0;
2991     uint8_t byteSIM[RESPONSE_EF_SIZE] = {0};
2992     for (i = 0; i < len; i++) {
2993         if (byteUSIM[i] == USIM_FILE_DES_TAG) {
2994             desIndex = i;
2995             break;
2996         }
2997     }
2998     for (i = desIndex; i < len;) {
2999         if (byteUSIM[i] == USIM_FILE_SIZE_TAG) {
3000             sizeIndex = i;
3001             break;
3002         } else {
3003             i += (byteUSIM[i + 1] + 2);
3004         }
3005     }
3006     byteSIM[RESPONSE_DATA_FILE_SIZE_1] =
3007             byteUSIM[sizeIndex + USIM_DATA_OFFSET_2];
3008     byteSIM[RESPONSE_DATA_FILE_SIZE_2] =
3009             byteUSIM[sizeIndex + USIM_DATA_OFFSET_3];
3010     byteSIM[RESPONSE_DATA_FILE_TYPE] = TYPE_EF;
3011     if ((byteUSIM[desIndex + RESPONSE_DATA_FILE_DES_FLAG] & 0x07) ==
3012         EF_TYPE_TRANSPARENT) {
3013         byteSIM[RESPONSE_DATA_STRUCTURE] = 0;
3014     } else if ((byteUSIM[desIndex + RESPONSE_DATA_FILE_DES_FLAG] & 0x07) ==
3015                 EF_TYPE_LINEAR_FIXED) {
3016         if (USIM_FILE_DES_TAG != byteUSIM[RESPONSE_DATA_FILE_DES_FLAG]) {
3017             RLOGE("USIM_FILE_DES_TAG != ...");
3018             goto error;
3019         }
3020         if (TYPE_FILE_DES_LEN != byteUSIM[RESPONSE_DATA_FILE_DES_LEN_FLAG]) {
3021             goto error;
3022         }
3023         byteSIM[RESPONSE_DATA_STRUCTURE] = 1;
3024         byteSIM[RESPONSE_DATA_RECORD_LENGTH] =
3025                 ((byteUSIM[RESPONSE_DATA_FILE_RECORD_LEN_1] & 0xff) << 8) +
3026                 (byteUSIM[RESPONSE_DATA_FILE_RECORD_LEN_2] & 0xff);
3027     } else if ((byteUSIM[desIndex + RESPONSE_DATA_FILE_DES_FLAG] & 0x07) ==
3028                 EF_TYPE_CYCLIC) {
3029         byteSIM[RESPONSE_DATA_STRUCTURE] = 3;
3030         byteSIM[RESPONSE_DATA_RECORD_LENGTH] =
3031                 ((byteUSIM[RESPONSE_DATA_FILE_RECORD_LEN_1] & 0xff) << 8) +
3032                 (byteUSIM[RESPONSE_DATA_FILE_RECORD_LEN_2] & 0xff);
3033     }
3034 
3035     convertBytesToHex(byteSIM, RESPONSE_EF_SIZE, hexSIM);
3036     return true;
3037 
3038 error:
3039     return false;
3040 }
3041 
3042 static void  requestSIM_IO(void *data, size_t datalen __unused, RIL_Token t)
3043 {
3044     ATResponse *p_response = NULL;
3045     RIL_SIM_IO_Response sr;
3046     int err;
3047     char *cmd = NULL;
3048     RIL_SIM_IO_v6 *p_args;
3049     char *line;
3050 
3051     /* For Convert USIM to SIM */
3052     uint8_t hexSIM[RESPONSE_EF_SIZE * 2 + sizeof(char)] = {0};
3053 
3054     memset(&sr, 0, sizeof(sr));
3055 
3056     p_args = (RIL_SIM_IO_v6 *)data;
3057 
3058     /* FIXME handle pin2 */
3059 
3060     if (p_args->data == NULL) {
3061         asprintf(&cmd, "AT+CRSM=%d,%d,%d,%d,%d",
3062                     p_args->command, p_args->fileid,
3063                     p_args->p1, p_args->p2, p_args->p3);
3064     } else {
3065         asprintf(&cmd, "AT+CRSM=%d,%d,%d,%d,%d,%s",
3066                     p_args->command, p_args->fileid,
3067                     p_args->p1, p_args->p2, p_args->p3, p_args->data);
3068     }
3069 
3070     err = at_send_command_singleline(cmd, "+CRSM:", &p_response);
3071 
3072     if (err < 0 || p_response->success == 0) {
3073         goto error;
3074     }
3075 
3076     line = p_response->p_intermediates->line;
3077 
3078     err = parseSimResponseLine(line, &sr);
3079     if (err < 0) {
3080         goto error;
3081     }
3082     if (sr.simResponse != NULL &&  // Default to be USIM card
3083         p_args->command == 192) {  // Get response
3084         uint8_t *bytes = convertHexStringToBytes(sr.simResponse, strlen(sr.simResponse));
3085         if (bytes == NULL) {
3086             RLOGE("Failed to convert sim response to bytes");
3087             goto error;
3088         }
3089         if (bytes[0] != 0x62) {
3090             RLOGE("Wrong FCP flag, unable to convert to sim ");
3091             free(bytes);
3092             goto error;
3093         }
3094         if (convertUsimToSim(bytes, strlen(sr.simResponse) / 2, hexSIM)) {
3095           sr.simResponse = (char *)hexSIM;
3096         }
3097         free(bytes);
3098     }
3099 
3100     RIL_onRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
3101     at_response_free(p_response);
3102     free(cmd);
3103     return;
3104 
3105 error:
3106     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3107     at_response_free(p_response);
3108     free(cmd);
3109 }
3110 
3111 static int getSimlockRemainTimes(const char* type) {
3112     int err = -1;
3113     int remain_times = -1;
3114     char cmd[32] = {0};
3115     char *line = NULL;
3116     char *lock_type = NULL;
3117     ATResponse *p_response = NULL;
3118 
3119     snprintf(cmd, sizeof(cmd), "AT+CPINR=\"%s\"", type);
3120     err = at_send_command_multiline(cmd, "+CPINR:", &p_response);
3121     if (err < 0 || p_response->success == 0) {
3122         goto error;
3123     }
3124 
3125     line = p_response->p_intermediates->line;
3126     err = at_tok_start(&line);
3127     if (err < 0) goto error;
3128 
3129     err = at_tok_nextstr(&line, &lock_type);
3130     if (err < 0) goto error;
3131 
3132     err = at_tok_nextint(&line, &remain_times);
3133     if (err < 0) goto error;
3134 
3135 error:
3136     at_response_free(p_response);
3137     return remain_times;
3138 }
3139 
3140 static void  requestEnterSimPin(int request, void*  data, size_t  datalen, RIL_Token  t)
3141 {
3142     ATResponse   *p_response = NULL;
3143     int           err;
3144     int           remaintimes = -1;
3145     char*         cmd = NULL;
3146     const char**  strings = (const char**)data;;
3147 
3148     if (datalen == sizeof(char*) || datalen == 2 * sizeof(char*)) {
3149         asprintf(&cmd, "AT+CPIN=%s", strings[0]);
3150     } else
3151         goto error;
3152 
3153     err = at_send_command_singleline(cmd, "+CPIN:", &p_response);
3154     free(cmd);
3155 
3156     if (err < 0 || p_response->success == 0) {
3157 error:
3158         if (request == RIL_REQUEST_ENTER_SIM_PIN) {
3159             remaintimes = getSimlockRemainTimes("SIM PIN");
3160         } else if (request == RIL_REQUEST_ENTER_SIM_PIN2) {
3161             remaintimes = getSimlockRemainTimes("SIM PIN2");
3162         }
3163         RIL_onRequestComplete(t, RIL_E_PASSWORD_INCORRECT, &remaintimes,
3164             sizeof(remaintimes));
3165     } else {
3166         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3167     }
3168     at_response_free(p_response);
3169 }
3170 
3171 static void  requestChangeSimPin(int request, void*  data, size_t  datalen, RIL_Token  t)
3172 {
3173     ATResponse   *p_response = NULL;
3174     int           err;
3175     int           remaintimes = -1;
3176     char*         cmd = NULL;
3177     const char**  strings = (const char**)data;;
3178 
3179     if (datalen == 2 * sizeof(char*) || datalen == 3 * sizeof(char*)) {
3180         asprintf(&cmd, "AT+CPIN=%s,%s", strings[0], strings[1]);
3181     } else
3182         goto error;
3183 
3184     err = at_send_command_singleline(cmd, "+CPIN:", &p_response);
3185     free(cmd);
3186 
3187     if (err < 0 || p_response->success == 0) {
3188 error:
3189         if (request == RIL_REQUEST_CHANGE_SIM_PIN) {
3190             remaintimes = getSimlockRemainTimes("SIM PIN");
3191         } else if (request == RIL_REQUEST_ENTER_SIM_PUK) {
3192             remaintimes = getSimlockRemainTimes("SIM PUK");
3193         } else if (request == RIL_REQUEST_ENTER_SIM_PUK2) {
3194           remaintimes = getSimlockRemainTimes("SIM PUK2");
3195         }
3196         RIL_onRequestComplete(t, RIL_E_PASSWORD_INCORRECT, &remaintimes,
3197             sizeof(remaintimes));
3198     } else {
3199         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3200     }
3201     at_response_free(p_response);
3202 }
3203 
3204 static void requestChangeSimPin2(void *data, size_t datalen, RIL_Token t) {
3205     int err, ret;
3206     int remaintime = -1;
3207     char cmd[64] = {0};
3208     const char **strings = (const char **)data;
3209     ATResponse *p_response = NULL;
3210 
3211     if (datalen != 3 * sizeof(char *)) {
3212         goto error;
3213     }
3214 
3215     snprintf(cmd, sizeof(cmd), "AT+CPWD=\"P2\",\"%s\",\"%s\"", strings[0],
3216              strings[1]);
3217     err = at_send_command(cmd, &p_response);
3218     if (err < 0 || p_response->success == 0) {
3219         remaintime = getSimlockRemainTimes("SIM PIN2");
3220         goto error;
3221     }
3222 
3223     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3224     at_response_free(p_response);
3225     return;
3226 
3227 error:
3228     RIL_onRequestComplete(t, RIL_E_PASSWORD_INCORRECT, &remaintime,
3229                           sizeof(remaintime));
3230     at_response_free(p_response);
3231 }
3232 
3233 static void  requestSendUSSD(void *data, size_t datalen, RIL_Token t)
3234 {
3235     RIL_UNUSED_PARM(datalen);
3236 
3237     int err = -1;
3238     char cmd[128] = {0};
3239     const char *ussdRequest = (char *)(data);
3240     ATResponse *p_response = NULL;
3241 
3242     snprintf(cmd, sizeof(cmd), "AT+CUSD=1,\"%s\"", ussdRequest);
3243     err = at_send_command(cmd, &p_response);
3244     if (err < 0 || p_response->success == 0) {
3245         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3246     } else {
3247         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3248     }
3249     at_response_free(p_response);
3250 }
3251 
3252 static void requestExitEmergencyMode(void *data __unused, size_t datalen __unused, RIL_Token t)
3253 {
3254     int err;
3255     ATResponse *p_response = NULL;
3256 
3257     err = at_send_command("AT+WSOS=0", &p_response);
3258 
3259     if (err < 0 || p_response->success == 0) {
3260         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3261         return;
3262     }
3263 
3264     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3265 }
3266 
3267 static uint64_t s_last_activity_info_query = 0;
3268 
3269 static void requestGetActivityInfo(void *data __unused, size_t datalen __unused, RIL_Token t)
3270 {
3271     uint64_t curTime = ril_nano_time();
3272     RIL_ActivityStatsInfo stats =
3273     {
3274         0, // sleep_mode_time_ms
3275         ((curTime - s_last_activity_info_query) / 1000000) - 1, // idle_mode_time_ms
3276         {0, 0, 0, 0, 0}, // tx_mode_time_ms
3277         0 // rx_mode_time_ms
3278     };
3279     s_last_activity_info_query = curTime;
3280 
3281     RIL_onRequestComplete(t, RIL_E_SUCCESS, &stats, sizeof(stats));
3282 }
3283 
3284 // TODO: Use all radio types
3285 static int techFromModemType(int mdmtype)
3286 {
3287     int ret = -1;
3288     switch (mdmtype) {
3289         case MDM_CDMA:
3290             ret = RADIO_TECH_1xRTT;
3291             break;
3292         case MDM_EVDO:
3293             ret = RADIO_TECH_EVDO_A;
3294             break;
3295         case MDM_GSM:
3296             ret = RADIO_TECH_GPRS;
3297             break;
3298         case MDM_WCDMA:
3299             ret = RADIO_TECH_HSPA;
3300             break;
3301         case MDM_LTE:
3302             ret = RADIO_TECH_LTE;
3303         case MDM_NR:
3304             ret = RADIO_TECH_NR;
3305             break;
3306     }
3307     return ret;
3308 }
3309 
3310 static void requestGetCellInfoList(void *data __unused, size_t datalen __unused, RIL_Token t)
3311 {
3312     uint64_t curTime = ril_nano_time();
3313     RIL_CellInfo_v12 ci[1] =
3314     {
3315         { // ci[0]
3316             1, // cellInfoType
3317             1, // registered
3318             RIL_TIMESTAMP_TYPE_MODEM,
3319             curTime - 1000, // Fake some time in the past
3320             { // union CellInfo
3321                 {  // RIL_CellInfoGsm gsm
3322                     {  // gsm.cellIdneityGsm
3323                         s_mcc, // mcc
3324                         s_mnc, // mnc
3325                         s_lac, // lac
3326                         s_cid, // cid
3327                         0, //arfcn unknown
3328                         0x1, // Base Station Identity Code set to arbitrarily 1
3329                     },
3330                     {  // gsm.signalStrengthGsm
3331                         10, // signalStrength
3332                         0  // bitErrorRate
3333                         , INT_MAX // timingAdvance invalid value
3334                     }
3335                 }
3336             }
3337         }
3338     };
3339 
3340     RIL_onRequestComplete(t, RIL_E_SUCCESS, ci, sizeof(ci));
3341 }
3342 
3343 static void requestGetCellInfoList_1_6(void* data __unused, size_t datalen __unused, RIL_Token t) {
3344     RIL_CellInfo_v16 ci[1] = {{    // ci[0]
3345                                3,  // cellInfoType
3346                                1,  // registered
3347                                CELL_CONNECTION_PRIMARY_SERVING,
3348                                {        // union CellInfo
3349                                 .lte = {// RIL_CellInfoLte_v12 lte
3350                                         {
3351                                                 // RIL_CellIdentityLte_v12
3352                                                 // lte.cellIdentityLte
3353                                                 s_mcc,  // mcc
3354                                                 s_mnc,  // mnc
3355                                                 s_cid,  // ci
3356                                                 0,      // pci
3357                                                 s_lac,  // tac
3358                                                 7,      // earfcn
3359                                         },
3360                                         {
3361                                                 // RIL_LTE_SignalStrength_v8
3362                                                 // lte.signalStrengthLte
3363                                                 10,      // signalStrength
3364                                                 44,      // rsrp
3365                                                 3,       // rsrq
3366                                                 30,      // rssnr
3367                                                 0,       // cqi
3368                                                 INT_MAX  // timingAdvance invalid value
3369                                         }}}}};
3370 
3371     RIL_onRequestComplete(t, RIL_E_SUCCESS, ci, sizeof(ci));
3372 }
3373 
3374 static void requestSetCellInfoListRate(void *data, size_t datalen __unused, RIL_Token t)
3375 {
3376     // For now we'll save the rate but no RIL_UNSOL_CELL_INFO_LIST messages
3377     // will be sent.
3378     assert (datalen == sizeof(int));
3379     s_cell_info_rate_ms = ((int *)data)[0];
3380 
3381     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3382 }
3383 
3384 static void requestGetHardwareConfig(void *data, size_t datalen, RIL_Token t)
3385 {
3386    // TODO - hook this up with real query/info from radio.
3387 
3388    RIL_HardwareConfig hwCfg;
3389 
3390    RIL_UNUSED_PARM(data);
3391    RIL_UNUSED_PARM(datalen);
3392 
3393    hwCfg.type = -1;
3394 
3395    RIL_onRequestComplete(t, RIL_E_SUCCESS, &hwCfg, sizeof(hwCfg));
3396 }
3397 
3398 static void requestGetTtyMode(void *data, size_t datalen, RIL_Token t)
3399 {
3400    int  ttyModeResponse;
3401 
3402    RIL_UNUSED_PARM(data);
3403    RIL_UNUSED_PARM(datalen);
3404 
3405    ttyModeResponse = (getSIMStatus() == SIM_READY) ? 1  // TTY Full
3406                                                    : 0; // TTY Off
3407 
3408    RIL_onRequestComplete(t, RIL_E_SUCCESS, &ttyModeResponse, sizeof(ttyModeResponse));
3409 }
3410 
3411 static void requestGetRadioCapability(void *data, size_t datalen, RIL_Token t)
3412 {
3413    RIL_RadioCapability radioCapability;
3414 
3415    RIL_UNUSED_PARM(data);
3416    RIL_UNUSED_PARM(datalen);
3417 
3418    radioCapability.version = RIL_RADIO_CAPABILITY_VERSION;
3419    radioCapability.session = 0;
3420    radioCapability.phase   = 0;
3421    radioCapability.rat     = NR | LTE | WCDMA | GSM;
3422    strncpy(radioCapability.logicalModemUuid, "com.android.modem.simulator", MAX_UUID_LENGTH);
3423    radioCapability.status  = RC_STATUS_SUCCESS;
3424 
3425    RIL_onRequestComplete(t, RIL_E_SUCCESS, &radioCapability, sizeof(radioCapability));
3426 }
3427 
3428 static void requestSetRadioCapability(void *data, size_t datalen, RIL_Token t)
3429 {
3430   RIL_RadioCapability* rc = (RIL_RadioCapability*)data;
3431   RLOGV(
3432       "RadioCapability version %d session %d phase %d rat %d "
3433       "logicalModemUuid %s status %d",
3434       rc->version, rc->session, rc->phase, rc->rat, rc->logicalModemUuid,
3435       rc->status);
3436   // TODO(ender): do something about these numbers.
3437   RIL_onRequestComplete(t, RIL_E_SUCCESS, rc, datalen);
3438 }
3439 
3440 static void requestGetMute(void *data, size_t datalen, RIL_Token t)
3441 {
3442     RIL_UNUSED_PARM(data);
3443     RIL_UNUSED_PARM(datalen);
3444 
3445     int err = -1;
3446     int muteResponse = 0;  // Mute disabled
3447     char *line = NULL;
3448     ATResponse *p_response = NULL;
3449 
3450     err = at_send_command_singleline("AT+CMUT?", "+CMUT:", &p_response);
3451     if (err < 0 || p_response->success) {
3452         goto done;
3453     }
3454 
3455     line = p_response->p_intermediates->line;
3456     err = at_tok_start(&line);
3457     if (err < 0) goto done;
3458 
3459     at_tok_nextint(&line, &muteResponse);
3460 
3461 done:
3462     RIL_onRequestComplete(t, RIL_E_SUCCESS, &muteResponse, sizeof(muteResponse));
3463     at_response_free(p_response);
3464 }
3465 
3466 static void requestSetMute(void *data, size_t datalen, RIL_Token t)
3467 {
3468     RIL_UNUSED_PARM(datalen);
3469 
3470     int err = -1;
3471     char cmd[64] = {0};
3472     ATResponse *p_response = NULL;
3473 
3474     snprintf(cmd, sizeof(cmd), "AT+CMUT=%d", ((int *)data)[0]);
3475     err = at_send_command(cmd, &p_response);
3476     if (err < 0 || p_response->success) {
3477       RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3478     } else {
3479       RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3480     }
3481     at_response_free(p_response);
3482 }
3483 
3484 static void requestScreenState(void *data, RIL_Token t)
3485 {
3486     int status = *((int *)data);
3487 
3488     if (!status) {
3489         /* Suspend */
3490         at_send_command("AT+CEREG=1", NULL);
3491         at_send_command("AT+CREG=1", NULL);
3492         at_send_command("AT+CGREG=1", NULL);
3493     } else {
3494        /* Resume */
3495         at_send_command("AT+CEREG=2", NULL);
3496         at_send_command("AT+CREG=2", NULL);
3497         at_send_command("AT+CGREG=2", NULL);
3498     }
3499 
3500    RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3501 }
3502 
3503 static void requestQueryClip(void *data, size_t datalen, RIL_Token t)
3504 {
3505     RIL_UNUSED_PARM(datalen);
3506     RIL_UNUSED_PARM(data);
3507 
3508     int err = -1;
3509     int skip = 0;
3510     int response = 0;
3511     char *line = NULL;
3512     ATResponse *p_response = NULL;
3513 
3514     if (getSIMStatus() == SIM_ABSENT) {
3515         RIL_onRequestComplete(t, RIL_E_MODEM_ERR, NULL, 0);
3516         return;
3517     }
3518 
3519     err = at_send_command_singleline("AT+CLIP?", "+CLIP:", &p_response);
3520     if (err < 0 || p_response->success == 0) {
3521         goto error;
3522     }
3523 
3524     line = p_response->p_intermediates->line;
3525     err = at_tok_start(&line);
3526     if (err < 0) goto error;
3527 
3528     err = at_tok_nextint(&line, &skip);
3529     if (err < 0) goto error;
3530 
3531     err = at_tok_nextint(&line, &response);
3532     if (err < 0) goto error;
3533 
3534     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
3535     at_response_free(p_response);
3536     return;
3537 
3538 error:
3539     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3540     at_response_free(p_response);
3541 }
3542 
3543 static void requestQueryClir(void *data, size_t datalen, RIL_Token t)
3544 {
3545     RIL_UNUSED_PARM(datalen);
3546     RIL_UNUSED_PARM(data);
3547 
3548     int err = -1;
3549     int response[2] = {1, 1};
3550     char *line = NULL;
3551     ATResponse *p_response = NULL;
3552 
3553     if (getSIMStatus() == SIM_ABSENT) {
3554         RIL_onRequestComplete(t, RIL_E_MODEM_ERR, NULL, 0);
3555         return;
3556     }
3557 
3558     err = at_send_command_singleline("AT+CLIR?", "+CLIR:", &p_response);
3559     if (err < 0 || p_response->success == 0) {
3560         goto error;
3561     }
3562 
3563     line = p_response->p_intermediates->line;
3564     err = at_tok_start(&line);
3565     if (err < 0) goto error;
3566 
3567     err = at_tok_nextint(&line, &response[0]);
3568     if (err < 0) goto error;
3569 
3570     err = at_tok_nextint(&line, &response[1]);
3571     if (err < 0) goto error;
3572 
3573     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
3574     at_response_free(p_response);
3575     return;
3576 
3577 error:
3578     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3579     at_response_free(p_response);
3580 }
3581 
3582 static void requestSetClir(void *data, size_t datalen, RIL_Token t)
3583 {
3584     RIL_UNUSED_PARM(datalen);
3585 
3586     int err = -1;
3587     int n = ((int *)data)[0];
3588     char cmd[64] = {0};
3589     ATResponse *p_response = NULL;
3590 
3591     snprintf(cmd, sizeof(cmd), "AT+CLIR=%d", n);
3592     err = at_send_command(cmd, &p_response);
3593     if (err < 0 || p_response->success == 0) {
3594         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3595     } else {
3596         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3597     }
3598     at_response_free(p_response);
3599 }
3600 
3601 static int forwardFromCCFCULine(char *line, RIL_CallForwardInfo *p_forward) {
3602     int err = -1;
3603     int i = 0;
3604 
3605     if (line == NULL || p_forward == NULL) {
3606       goto error;
3607     }
3608 
3609     err = at_tok_start(&line);
3610     if (err < 0) goto error;
3611 
3612     err = at_tok_nextint(&line, &(p_forward->status));
3613     if (err < 0) goto error;
3614 
3615     err = at_tok_nextint(&line, &(p_forward->serviceClass));
3616     if (err < 0) goto error;
3617 
3618     if (at_tok_hasmore(&line)) {
3619         int numberType = 0;
3620         err = at_tok_nextint(&line, &numberType);
3621         if (err < 0) goto error;
3622 
3623         err = at_tok_nextint(&line, &p_forward->toa);
3624         if (err < 0) goto error;
3625 
3626         err = at_tok_nextstr(&line, &(p_forward->number));
3627 
3628         /* tolerate null here */
3629         if (err < 0) return 0;
3630 
3631         if (at_tok_hasmore(&line)) {
3632             for (i = 0; i < 2; i++) {
3633                 skipNextComma(&line);
3634             }
3635 
3636             if (at_tok_hasmore(&line)) {
3637                 err = at_tok_nextint(&line, &p_forward->timeSeconds);
3638                 if (err < 0) {
3639                     p_forward->timeSeconds = 0;
3640                 }
3641             }
3642         }
3643     }
3644 
3645     return 0;
3646 
3647 error:
3648     return -1;
3649 }
3650 
3651 static void requestSetCallForward(RIL_CallForwardInfo *data,
3652                                   size_t datalen, RIL_Token t) {
3653     int err = -1;
3654     char cmd[128] = {0};
3655     size_t offset = 0;
3656     ATResponse *p_response = NULL;
3657 
3658     if (datalen != sizeof(*data) ||
3659             (data->status == 3 && data->number == NULL)) {
3660         goto error;
3661     }
3662 
3663     snprintf(cmd, sizeof(cmd), "AT+CCFCU=%d,%d,%d,%d,\"%s\",%d",
3664                             data->reason,
3665                             data->status,
3666                             2,
3667                             data->toa,
3668                             data->number ? data->number : "",
3669                             data->serviceClass);
3670     offset += strlen(cmd);
3671 
3672     if (data->serviceClass == 0) {
3673         if (data->timeSeconds != 0 && data->status == 3) {
3674             snprintf(cmd + offset, sizeof(cmd) - offset, ",\"\",\"\",,%d",
3675                 data->timeSeconds);
3676         }
3677     } else {
3678         if (data->timeSeconds != 0 && data->status == 3) {
3679             snprintf(cmd + offset, sizeof(cmd) - offset, ",\"\",\"\",,%d",
3680                 data->timeSeconds);
3681         } else {
3682             strlcat(cmd, ",\"\"", sizeof(cmd) - offset);
3683         }
3684     }
3685 
3686     err = at_send_command_multiline(cmd, "+CCFCU:", &p_response);
3687     if (err < 0 || p_response->success == 0) {
3688         goto error;
3689     }
3690 
3691     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3692     at_response_free(p_response);
3693     return;
3694 
3695 error:
3696     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3697     at_response_free(p_response);
3698 }
3699 
3700 static void requestQueryCallForward(RIL_CallForwardInfo *data,
3701                                     size_t datalen, RIL_Token t) {
3702     int err = -1;
3703     char cmd[128] = {0};
3704     ATResponse *p_response = NULL;
3705     ATLine *p_cur = NULL;
3706 
3707     if (datalen != sizeof(*data)) {
3708         goto error;
3709     }
3710 
3711     snprintf(cmd, sizeof(cmd), "AT+CCFCU=%d,2,%d,%d,\"%s\",%d", data->reason, 2,
3712             data->toa, data->number ? data->number : "", data->serviceClass);
3713 
3714     err = at_send_command_multiline(cmd, "+CCFCU:", &p_response);
3715     if (err < 0 || p_response->success == 0) {
3716         goto error;
3717     }
3718 
3719     RIL_CallForwardInfo **forwardList = NULL, *forwardPool = NULL;
3720     int forwardCount = 0;
3721     int validCount = 0;
3722     int i = 0;
3723 
3724     for (p_cur = p_response->p_intermediates; p_cur != NULL;
3725          p_cur = p_cur->p_next, forwardCount++) {
3726     }
3727 
3728     forwardList = (RIL_CallForwardInfo **)
3729         alloca(forwardCount * sizeof(RIL_CallForwardInfo *));
3730 
3731     forwardPool = (RIL_CallForwardInfo *)
3732         alloca(forwardCount * sizeof(RIL_CallForwardInfo));
3733 
3734     memset(forwardPool, 0, forwardCount * sizeof(RIL_CallForwardInfo));
3735 
3736     /* init the pointer array */
3737     for (i = 0; i < forwardCount; i++) {
3738         forwardList[i] = &(forwardPool[i]);
3739     }
3740 
3741     for (p_cur = p_response->p_intermediates; p_cur != NULL;
3742          p_cur = p_cur->p_next) {
3743         err = forwardFromCCFCULine(p_cur->line, forwardList[validCount]);
3744         forwardList[validCount]->reason = data->reason;
3745         if (err == 0) validCount++;
3746     }
3747 
3748     RIL_onRequestComplete(t, RIL_E_SUCCESS, validCount ? forwardList : NULL,
3749                           validCount * sizeof (RIL_CallForwardInfo *));
3750     at_response_free(p_response);
3751     return;
3752 
3753 error:
3754     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3755     at_response_free(p_response);
3756 }
3757 
3758 static void requestQueryCallWaiting(void *data, size_t datalen, RIL_Token t) {
3759     RIL_UNUSED_PARM(datalen);
3760 
3761     int err = -1, mode = 0;
3762     int serviceClass = ((int *)data)[0];
3763     int response[2] = {0, 0};
3764     char cmd[32] = {0};
3765     char *line;
3766     ATLine *p_cur;
3767     ATResponse *p_response = NULL;
3768 
3769     if (serviceClass == 0) {
3770         snprintf(cmd, sizeof(cmd), "AT+CCWA=1,2");
3771     } else {
3772         snprintf(cmd, sizeof(cmd), "AT+CCWA=1,2,%d", serviceClass);
3773     }
3774     err = at_send_command_multiline(cmd, "+CCWA:", &p_response);
3775     if (err < 0 || p_response->success == 0) {
3776         goto error;
3777     }
3778 
3779     for (p_cur = p_response->p_intermediates; p_cur != NULL;
3780          p_cur = p_cur->p_next) {
3781         line = p_cur->line;
3782         err = at_tok_start(&line);
3783         if (err < 0) goto error;
3784 
3785         err = at_tok_nextint(&line, &mode);
3786         if (err < 0) goto error;
3787 
3788         err = at_tok_nextint(&line, &serviceClass);
3789         if (err < 0) goto error;
3790 
3791         response[0] = mode;
3792         response[1] |= serviceClass;
3793     }
3794     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
3795     at_response_free(p_response);
3796     return;
3797 
3798 error:
3799     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3800     at_response_free(p_response);
3801 }
3802 
3803 static void requestSetCallWaiting(void *data, size_t datalen, RIL_Token t) {
3804     RIL_UNUSED_PARM(datalen);
3805 
3806     ATResponse *p_response = NULL;
3807     int err = -1;
3808     char cmd[32] = {0};
3809     int enable = ((int *)data)[0];
3810     int serviceClass = ((int *)data)[1];
3811 
3812     if (serviceClass == 0) {
3813         snprintf(cmd, sizeof(cmd), "AT+CCWA=1,%d", enable);
3814     } else {
3815         snprintf(cmd, sizeof(cmd), "AT+CCWA=1,%d,%d", enable, serviceClass);
3816     }
3817 
3818     err = at_send_command(cmd,  &p_response);
3819     if (err < 0 || p_response->success == 0) {
3820         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3821     } else {
3822         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3823     }
3824     at_response_free(p_response);
3825 }
3826 
3827 static void requestSetSuppServiceNotifications(void *data, size_t datalen,
3828                                                RIL_Token t) {
3829     RIL_UNUSED_PARM(datalen);
3830 
3831     int err = 0;
3832     ATResponse *p_response = NULL;
3833     int mode = ((int *)data)[0];
3834     char cmd[32] = {0};
3835 
3836     snprintf(cmd, sizeof(cmd), "AT+CSSN=%d,%d", mode, mode);
3837     err = at_send_command(cmd, &p_response);
3838     if (err < 0 || p_response->success == 0) {
3839         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3840     } else {
3841         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3842     }
3843     at_response_free(p_response);
3844 }
3845 
3846 static void requestChangeBarringPassword(char **data, size_t datalen, RIL_Token t) {
3847     int err = -1;
3848     int result;
3849     char cmd[64] = {0};
3850     ATResponse *p_response = NULL;
3851 
3852     if (datalen != 3 * sizeof(char *) || data[0] == NULL || data[1] == NULL ||
3853         data[2] == NULL || strlen(data[0]) == 0 ||  strlen(data[1]) == 0 ||
3854         strlen(data[2]) == 0) {
3855         RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
3856         return;
3857     }
3858 
3859     snprintf(cmd, sizeof(cmd), "AT+CPWD=\"%s\",\"%s\",\"%s\"", data[0], data[1],
3860              data[2]);
3861 
3862     err = at_send_command(cmd, &p_response);
3863     if (err < 0 || p_response->success == 0) {
3864         goto error;
3865     }
3866     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3867     at_response_free(p_response);
3868     return;
3869 
3870 error:
3871     RIL_onRequestComplete(t, RIL_E_PASSWORD_INCORRECT, NULL, 0);
3872     at_response_free(p_response);
3873 }
3874 
3875 static void requestFacilityLock(int request, char **data,
3876                                 size_t datalen, RIL_Token t) {
3877     int err = -1;
3878     int status = 0;
3879     int serviceClass = 0;
3880     int remainTimes = 10;
3881     char cmd[128] = {0};
3882     char *line = NULL;
3883     ATLine *p_cur = NULL;
3884     ATResponse *p_response = NULL;
3885     RIL_Errno errnoType = RIL_E_GENERIC_FAILURE;
3886 
3887     char *type = data[0];
3888 
3889     if (datalen != 5 * sizeof(char *)) {
3890         goto error;
3891     }
3892     if (data[0] == NULL || data[1] == NULL ||
3893        (data[2] == NULL && request == RIL_REQUEST_SET_FACILITY_LOCK) ||
3894         strlen(data[0]) == 0 || strlen(data[1]) == 0 ||
3895        (request == RIL_REQUEST_SET_FACILITY_LOCK && strlen(data[2]) == 0 )) {
3896         errnoType = RIL_E_INVALID_ARGUMENTS;
3897         RLOGE("FacilityLock invalid arguments");
3898         goto error;
3899     }
3900 
3901     serviceClass = atoi(data[3]);
3902     if (serviceClass == 0) {
3903         snprintf(cmd, sizeof(cmd), "AT+CLCK=\"%s\",%c,\"%s\"", data[0], *data[1],
3904                  data[2]);
3905     } else {
3906         snprintf(cmd, sizeof(cmd), "AT+CLCK=\"%s\",%c,\"%s\",%s", data[0],
3907                  *data[1], data[2], data[3]);
3908     }
3909 
3910     if (*data[1] == '2') {  // query status
3911         err = at_send_command_multiline(cmd, "+CLCK: ", &p_response);
3912         if (err < 0 || p_response->success == 0) {
3913             goto error;
3914         }
3915         line = p_response->p_intermediates->line;
3916 
3917         err = at_tok_start(&line);
3918         if (err < 0) goto error;
3919 
3920         err = at_tok_nextint(&line, &status);
3921         if (err < 0) goto error;
3922 
3923         RIL_onRequestComplete(t, RIL_E_SUCCESS, &status, sizeof(int));
3924         at_response_free(p_response);
3925         return;
3926     } else {  // unlock/lock this facility
3927         err = at_send_command(cmd, &p_response);
3928         if (err < 0 || p_response->success == 0) {
3929             errnoType = RIL_E_PASSWORD_INCORRECT;
3930             goto error;
3931         }
3932         errnoType = RIL_E_SUCCESS;
3933     }
3934 
3935 error:
3936     if (!strcmp(data[0], "SC")) {
3937         remainTimes = getSimlockRemainTimes("SIM PIN");
3938     } else if (!strcmp(data[0], "FD")) {
3939         remainTimes = getSimlockRemainTimes("SIM PIN2");
3940     } else {
3941         remainTimes = 1;
3942     }
3943 
3944     RIL_onRequestComplete(t, errnoType, &remainTimes, sizeof(remainTimes));
3945     at_response_free(p_response);
3946 }
3947 
3948 static void requestSetSmscAddress(void *data, size_t datalen, RIL_Token t)
3949 {
3950     ATResponse   *p_response = NULL;
3951     char          cmd[64] = {0};
3952     int           err = -1;
3953 
3954     if (getSIMStatus() != SIM_READY) {
3955          RIL_onRequestComplete(t, RIL_E_SIM_ABSENT, NULL, 0);
3956          return;
3957     }
3958 
3959     if (data == NULL || strlen(data) == 0) {
3960         RLOGE("SET_SMSC_ADDRESS invalid address: %s", (char *)data);
3961         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3962         return;
3963     }
3964 
3965     snprintf(cmd, sizeof(cmd), "AT+CSCA=%s,%d", (char *)data, (int)datalen);
3966 
3967     err = at_send_command_singleline(cmd, "+CSCA:", &p_response);
3968     if (err < 0 || p_response->success == 0) {
3969         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
3970     } else {
3971         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
3972     }
3973     at_response_free(p_response);
3974 }
3975 
3976 static void requestGetSmscAddress(void *data, size_t datalen, RIL_Token t)
3977 {
3978     RIL_UNUSED_PARM(data);
3979     RIL_UNUSED_PARM(datalen);
3980 
3981     ATResponse   *p_response = NULL;
3982     int           err = -1;
3983     char         *decidata = NULL;
3984 
3985     err = at_send_command_singleline( "AT+CSCA?", "+CSCA:", &p_response);
3986     if (err < 0 || p_response->success == 0) {
3987        goto error;
3988     }
3989 
3990     char *line = p_response->p_intermediates->line;
3991     err = at_tok_start(&line);
3992     if (err < 0) goto error;
3993 
3994     err = at_tok_nextstr(&line, &decidata);
3995     if (err < 0) goto error;
3996 
3997     RIL_onRequestComplete(t, RIL_E_SUCCESS, decidata, strlen(decidata) + 1);
3998     at_response_free(p_response);
3999     return;
4000 
4001 error:
4002     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4003     at_response_free(p_response);
4004 }
4005 
4006 static void setGsmBroadcastConfigData(int from, int to, int id, int outStrSize, char *outStr) {
4007     if (from < 0 || from > 0xffff || to < 0 || to > 0xffff) {
4008         RLOGE("setGsmBroadcastConfig data is invalid, [%d, %d]", from, to);
4009         return;
4010     }
4011 
4012     if (id != 0) {
4013         strlcat(outStr, ",", outStrSize);
4014     }
4015 
4016     int len = strlen(outStr);
4017     if (from == to) {
4018         snprintf(outStr + len, outStrSize - len, "%d", from);
4019     } else {
4020         snprintf(outStr + len, outStrSize - len, "%d-%d", from, to);
4021     }
4022 }
4023 
4024 static void requestSetSmsBroadcastConfig(void *data, size_t datalen,
4025                                          RIL_Token t) {
4026     int i = 0;
4027     int count = datalen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
4028     int size = count * 16;
4029     char cmd[256] = {0};
4030     char *channel = (char *)alloca(size);
4031     char *languageId = (char *)alloca(size);
4032     ATResponse *p_response = NULL;
4033     RIL_GSM_BroadcastSmsConfigInfo **pGsmBci =
4034             (RIL_GSM_BroadcastSmsConfigInfo **)data;
4035     RIL_GSM_BroadcastSmsConfigInfo gsmBci = {0};
4036 
4037     memset(channel, 0, size);
4038     memset(languageId, 0, size);
4039     RLOGD("requestSetGsmBroadcastConfig %zu, count %d", datalen, count);
4040 
4041     for (i = 0; i < count; i++) {
4042         gsmBci = *(pGsmBci[i]);
4043         setGsmBroadcastConfigData(gsmBci.fromServiceId, gsmBci.toServiceId, i,
4044                                   size, channel);
4045         setGsmBroadcastConfigData(gsmBci.fromCodeScheme, gsmBci.toCodeScheme, i,
4046                                   size, languageId);
4047     }
4048 
4049     snprintf(cmd, sizeof(cmd), "AT+CSCB=%d,\"%s\",\"%s\"",
4050             (*pGsmBci[0]).selected ? 0 : 1, channel, languageId);
4051     int err = at_send_command_singleline( cmd, "+CSCB:", &p_response);
4052 
4053     if (err < 0 || p_response->success == 0) {
4054         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4055     } else {
4056         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4057     }
4058     at_response_free(p_response);
4059 }
4060 
4061 static void requestGetSmsBroadcastConfig(void *data, size_t datalen,
4062                                          RIL_Token t) {
4063     RIL_UNUSED_PARM(data);
4064     RIL_UNUSED_PARM(datalen);
4065 
4066     ATResponse *p_response = NULL;
4067     int err = -1, mode, commas = 0, i = 0;
4068     char *line = NULL;
4069     char *serviceIds = NULL, *codeSchemes = NULL, *p = NULL;
4070     char *serviceId = NULL, *codeScheme = NULL;
4071 
4072     err = at_send_command_singleline("AT+CSCB?", "+CSCB:", &p_response);
4073     if (err < 0 || p_response->success == 0) {
4074         goto error;
4075     }
4076 
4077     line = p_response->p_intermediates->line;
4078     err = at_tok_start(&line);
4079     if (err < 0) goto error;
4080 
4081     err = at_tok_nextint(&line, &mode);
4082     if (err < 0) goto error;
4083 
4084     err = at_tok_nextstr(&line, &serviceIds);
4085     if (err < 0) goto error;
4086 
4087     err = at_tok_nextstr(&line, &codeSchemes);
4088     if (err < 0) goto error;
4089 
4090     for (p = serviceIds; *p != '\0'; p++) {
4091         if (*p == ',') {
4092             commas++;
4093         }
4094     }
4095     RIL_GSM_BroadcastSmsConfigInfo **pGsmBci =
4096         (RIL_GSM_BroadcastSmsConfigInfo **)alloca((commas + 1) *
4097             sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
4098     memset(pGsmBci, 0, (commas + 1) * sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
4099 
4100     for (i = 0; i < commas + 1; i++) {
4101         pGsmBci[i] = (RIL_GSM_BroadcastSmsConfigInfo *)alloca(
4102                 sizeof(RIL_GSM_BroadcastSmsConfigInfo));
4103         memset(pGsmBci[i], 0, sizeof(RIL_GSM_BroadcastSmsConfigInfo));
4104 
4105         err = at_tok_nextstr(&serviceIds, &serviceId);
4106         if (err < 0) goto error;
4107         pGsmBci[i]->toServiceId = pGsmBci[i]->fromServiceId = 0;
4108         if (strstr(serviceId, "-")) {
4109             sscanf(serviceId,"%d-%d", &pGsmBci[i]->fromServiceId,
4110                    &pGsmBci[i]->toServiceId);
4111         }
4112 
4113         err = at_tok_nextstr(&codeSchemes, &codeScheme);
4114         if (err < 0) goto error;
4115         pGsmBci[i]->toCodeScheme = pGsmBci[i]->fromCodeScheme = 0;
4116         if (strstr(codeScheme, "-")) {
4117             sscanf(codeScheme, "%d-%d", &pGsmBci[i]->fromCodeScheme,
4118                    &pGsmBci[i]->toCodeScheme);
4119         }
4120 
4121         pGsmBci[i]->selected = (mode == 0 ? false : true);
4122     }
4123     RIL_onRequestComplete(t, RIL_E_SUCCESS, pGsmBci,
4124         (commas + 1) * sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
4125     at_response_free(p_response);
4126     return;
4127 
4128 error:
4129     at_response_free(p_response);
4130     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4131 }
4132 
4133 /**
4134  * <AcT>: integer type; access technology selected
4135  * 0 GSM
4136  * 1 GSM Compact
4137  * 2 UTRAN
4138  * 3 GSM w/EGPRS (see NOTE 1)
4139  * 4 UTRAN w/HSDPA (see NOTE 2)
4140  * 5 UTRAN w/HSUPA (see NOTE 2)
4141  * 6 UTRAN w/HSDPA and HSUPA (see NOTE 2)
4142  * 7 E-UTRAN
4143  * 8 EC-GSM-IoT (A/Gb mode) (see NOTE 3)
4144  * 9 E-UTRAN (NB-S1 mode) (see NOTE 4)
4145  * 10  E-UTRA connected to a 5GCN (see NOTE 5)
4146  * 11  NR connected to a 5GCN (see NOTE 5)
4147  * 12  NG-RAN
4148  * 13  E-UTRA-NR dual connectivity (see NOTE 6)
4149  */
4150 int mapRadioAccessNetworkToTech(RIL_RadioAccessNetworks network) {
4151     switch (network) {
4152         case GERAN:  // GSM EDGE
4153             return 3;
4154         case UTRAN:
4155             return 6;
4156         case EUTRAN:
4157             return 7;
4158         case NGRAN:
4159             return 11;
4160         default:
4161             return 7;  // LTE
4162     }
4163 }
4164 
4165 static void requestSetNetworlSelectionManual(void *data, RIL_Token t) {
4166     int err = -1;
4167     char cmd[64] = {0};
4168     ATResponse *p_response = NULL;
4169     RIL_NetworkOperator *operator = (RIL_NetworkOperator *)data;
4170 
4171     if (operator->act != UNKNOWN) {
4172         snprintf(cmd, sizeof(cmd), "AT+COPS=1,2,\"%s\"", operator->operatorNumeric);
4173     } else {
4174         snprintf(cmd, sizeof(cmd), "AT+COPS=1,2,\"%s\",%d",
4175             operator->operatorNumeric, operator->act);
4176     }
4177     err = at_send_command(cmd, &p_response);
4178     if (err < 0 || p_response->success == 0) {
4179         goto error;
4180     }
4181 
4182     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4183     at_response_free(p_response);
4184     return;
4185 
4186 error:
4187     if (p_response != NULL &&
4188         !strcmp(p_response->finalResponse, "+CME ERROR: 30")) {
4189           RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
4190     } else {
4191         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4192     }
4193     at_response_free(p_response);
4194 }
4195 
4196 static void requestStkServiceIsRunning(RIL_Token t)
4197 {
4198     int err = -1;
4199     ATResponse *p_response = NULL;
4200 
4201     s_stkServiceRunning = true;
4202     if (NULL != s_stkUnsolResponse) {
4203        RIL_onUnsolicitedResponse(RIL_UNSOL_STK_PROACTIVE_COMMAND,
4204                             s_stkUnsolResponse, strlen(s_stkUnsolResponse) + 1);
4205        free(s_stkUnsolResponse);
4206        s_stkUnsolResponse = NULL;
4207        RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4208        return;
4209     }
4210 
4211     err = at_send_command_singleline("AT+CUSATD?", "+CUSATD:", &p_response);
4212 
4213     if (err < 0 || p_response->success == 0) {
4214         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4215     } else {
4216         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4217     }
4218     at_response_free(p_response);
4219 }
4220 
4221 static void requestStkSendEnvelope(void *data, RIL_Token t)
4222 {
4223     int ret = -1, err = -1;
4224     char cmd[128] = {0};
4225     ATResponse *p_response = NULL;
4226 
4227     if (data == NULL || strlen((char *)data) == 0) {
4228         RLOGE("STK sendEnvelope data is invalid");
4229         RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
4230         return;
4231     }
4232 
4233     snprintf(cmd, sizeof(cmd), "AT+CUSATE=\"%s\"", (char *)data);
4234     err = at_send_command_singleline(cmd, "+CUSATE:", &p_response);
4235     if (err < 0 || p_response->success == 0) {
4236         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4237     } else {
4238         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4239 
4240         // type of alpha data is 85, such as 850C546F6F6C6B6974204D656E75
4241         char *p = strstr(p_response->p_intermediates->line, "85");
4242         if (p != NULL) {
4243             char alphaStrHexLen[3] = {0};
4244             char alphaStr[1024] = {0};
4245             uint8_t *alphaBytes = NULL;
4246             int len = 0;
4247 
4248             p = p + strlen("85");
4249             strncpy(alphaStrHexLen, p, 2);
4250             len = strtoul(alphaStrHexLen, NULL, 16);
4251             strncpy(alphaStr, p + 2, len * 2);
4252             alphaBytes = convertHexStringToBytes(alphaStr, strlen(alphaStr));
4253             RIL_onUnsolicitedResponse(RIL_UNSOL_STK_CC_ALPHA_NOTIFY, alphaBytes,
4254                                       strlen((char *)alphaBytes));
4255             free(alphaBytes);
4256         }
4257     }
4258     at_response_free(p_response);
4259 }
4260 
4261 static void requestStksendTerminalResponse(void *data, RIL_Token t)
4262 {
4263     int ret = -1, err = -1;
4264     char cmd[128] = {0};
4265     ATResponse *p_response = NULL;
4266 
4267     if (data == NULL || strlen((char *)data) == 0) {
4268         RLOGE("STK sendTerminalResponse data is invalid");
4269         RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
4270         return;
4271     }
4272 
4273     snprintf(cmd, sizeof(cmd), "AT+CUSATT=\"%s\"", (char *)data);
4274     err = at_send_command_singleline( cmd, "+CUSATT:", &p_response);
4275     if (err < 0 || p_response->success == 0) {
4276         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4277     } else {
4278         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4279     }
4280     at_response_free(p_response);
4281 }
4282 
4283 static void requestEccDial(void *data, RIL_Token t) {
4284     char cmd[64] = {0};
4285     const char *clir = NULL;
4286     int err = -1;
4287     RIL_EmergencyDial *p_eccDial = (RIL_EmergencyDial *)data;
4288 
4289     switch (p_eccDial->dialInfo.clir) {
4290         case 0:  /* subscription default */
4291             clir = "";
4292             break;
4293         case 1:  /* invocation */
4294             clir = "I";
4295             break;
4296         case 2:  /* suppression */
4297             clir = "i";
4298             break;
4299         default:
4300             break;
4301     }
4302 
4303     if (p_eccDial->routing == ROUTING_MERGENCY ||
4304         p_eccDial->routing ==  ROUTING_UNKNOWN) {
4305       if (p_eccDial->categories == CATEGORY_UNSPECIFIED) {
4306           snprintf(cmd, sizeof(cmd), "ATD%s@,#%s;", p_eccDial->dialInfo.address, clir);
4307       } else {
4308           snprintf(cmd, sizeof(cmd), "ATD%s@%d,#%s;", p_eccDial->dialInfo.address,
4309               p_eccDial->categories, clir);
4310       }
4311     } else {  // ROUTING_NORMAL
4312         snprintf(cmd, sizeof(cmd), "ATD%s%s;", p_eccDial->dialInfo.address, clir);
4313     }
4314 
4315     err = at_send_command(cmd, NULL);
4316     if (err != 0) goto error;
4317 
4318     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4319     return;
4320 
4321 error:
4322     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4323 }
4324 
4325 static void requestStartKeepalive(RIL_Token t) {
4326     RIL_KeepaliveStatus resp;
4327     resp.sessionHandle = s_session_handle++;
4328     resp.code = KEEPALIVE_ACTIVE;
4329     RIL_onRequestComplete(t, RIL_E_SUCCESS, &resp, sizeof(resp));
4330 }
4331 
4332 void getConfigSlotStatus(RIL_SimSlotStatus_V1_2 *pSimSlotStatus) {
4333     if (pSimSlotStatus == NULL) {
4334         return;
4335     }
4336     if (getSIMStatus() == SIM_ABSENT) {
4337         pSimSlotStatus->base.cardState = RIL_CARDSTATE_ABSENT;
4338     } else {
4339         pSimSlotStatus->base.cardState = RIL_CARDSTATE_PRESENT;
4340     }
4341     // TODO: slot state is always active now
4342     pSimSlotStatus->base.slotState = SLOT_STATE_ACTIVE;
4343 
4344     if (pSimSlotStatus->base.cardState != RIL_CARDSTATE_ABSENT) {
4345         pSimSlotStatus->base.atr = "";
4346         pSimSlotStatus->base.iccid = (char *)calloc(64, sizeof(char));
4347         getIccId(pSimSlotStatus->base.iccid, 64);
4348     }
4349 
4350     pSimSlotStatus->base.logicalSlotId = 0;
4351     pSimSlotStatus->eid = "";
4352 }
4353 
4354 void sendUnsolNetworkScanResult() {
4355     RIL_NetworkScanResult scanr;
4356     memset(&scanr, 0, sizeof(scanr));
4357     scanr.status = COMPLETE;
4358     scanr.error = RIL_E_SUCCESS;
4359     scanr.network_infos = NULL;
4360     scanr.network_infos_length = 0;
4361     RIL_onUnsolicitedResponse(RIL_UNSOL_NETWORK_SCAN_RESULT, &scanr, sizeof(scanr));
4362 }
4363 
4364 void onIccSlotStatus(RIL_Token t) {
4365     RIL_SimSlotStatus_V1_2 *pSimSlotStatusList =
4366         (RIL_SimSlotStatus_V1_2 *)calloc(SIM_COUNT, sizeof(RIL_SimSlotStatus_V1_2));
4367 
4368     getConfigSlotStatus(pSimSlotStatusList);
4369 
4370     if (t == NULL) {
4371         RIL_onUnsolicitedResponse(RIL_UNSOL_CONFIG_ICC_SLOT_STATUS, pSimSlotStatusList,
4372                  SIM_COUNT * sizeof(RIL_SimSlotStatus_V1_2));
4373     } else {
4374         RIL_onRequestComplete(t, RIL_E_SUCCESS, pSimSlotStatusList,
4375                 SIM_COUNT * sizeof(RIL_SimSlotStatus_V1_2));
4376     }
4377 
4378     if (pSimSlotStatusList != NULL) {
4379         free(pSimSlotStatusList->base.iccid);
4380         free(pSimSlotStatusList);
4381     }
4382 }
4383 
4384 /*** Callback methods from the RIL library to us ***/
4385 
4386 /**
4387  * Call from RIL to us to make a RIL_REQUEST
4388  *
4389  * Must be completed with a call to RIL_onRequestComplete()
4390  *
4391  * RIL_onRequestComplete() may be called from any thread, before or after
4392  * this function returns.
4393  *
4394  * Because onRequest function could be called from multiple different thread,
4395  * we must ensure that the underlying at_send_command_* function
4396  * is atomic.
4397  */
4398 static void
4399 onRequest (int request, void *data, size_t datalen, RIL_Token t)
4400 {
4401     ATResponse *p_response;
4402     int err;
4403 
4404     RLOGD("onRequest: %s, sState: %d", requestToString(request), sState);
4405 
4406     /* Ignore all requests except RIL_REQUEST_GET_SIM_STATUS
4407      * when RADIO_STATE_UNAVAILABLE.
4408      */
4409     if (sState == RADIO_STATE_UNAVAILABLE
4410         && request != RIL_REQUEST_GET_SIM_STATUS
4411     ) {
4412         RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
4413         return;
4414     }
4415 
4416     /* Ignore all non-power requests when RADIO_STATE_OFF
4417      * (except RIL_REQUEST_GET_SIM_STATUS)
4418      */
4419     if (sState == RADIO_STATE_OFF) {
4420         switch(request) {
4421             case RIL_REQUEST_BASEBAND_VERSION:
4422             case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
4423             case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:
4424             case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:
4425             case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
4426             case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
4427             case RIL_REQUEST_CDMA_SUBSCRIPTION:
4428             case RIL_REQUEST_DEVICE_IDENTITY:
4429             case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
4430             case RIL_REQUEST_GET_ACTIVITY_INFO:
4431             case RIL_REQUEST_GET_CARRIER_RESTRICTIONS:
4432             case RIL_REQUEST_GET_CURRENT_CALLS:
4433             case RIL_REQUEST_GET_IMEI:
4434             case RIL_REQUEST_GET_MUTE:
4435             case RIL_REQUEST_SET_MUTE:
4436             case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
4437             case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
4438             case RIL_REQUEST_GET_RADIO_CAPABILITY:
4439             case RIL_REQUEST_GET_SIM_STATUS:
4440             case RIL_REQUEST_NV_RESET_CONFIG:
4441             case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE:
4442             case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
4443             case RIL_REQUEST_QUERY_TTY_MODE:
4444             case RIL_REQUEST_RADIO_POWER:
4445             case RIL_REQUEST_SET_BAND_MODE:
4446             case RIL_REQUEST_SET_CARRIER_RESTRICTIONS:
4447             case RIL_REQUEST_SET_LOCATION_UPDATES:
4448             case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
4449             case RIL_REQUEST_SET_TTY_MODE:
4450             case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
4451             case RIL_REQUEST_STOP_LCE:
4452             case RIL_REQUEST_VOICE_RADIO_TECH:
4453             case RIL_REQUEST_SCREEN_STATE:
4454                 // Process all the above, even though the radio is off
4455                 break;
4456 
4457             default:
4458                 // For all others, say NOT_AVAILABLE because the radio is off
4459                 RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
4460                 return;
4461         }
4462     }
4463 
4464     switch (request) {
4465         case RIL_REQUEST_GET_SIM_STATUS: {
4466             RIL_CardStatus_v1_5 *p_card_status;
4467             char *p_buffer;
4468             int buffer_size;
4469 
4470             int result = getCardStatus(&p_card_status);
4471             if (result == RIL_E_SUCCESS) {
4472                 p_buffer = (char *)p_card_status;
4473                 buffer_size = sizeof(*p_card_status);
4474             } else {
4475                 p_buffer = NULL;
4476                 buffer_size = 0;
4477             }
4478             RIL_onRequestComplete(t, result, p_buffer, buffer_size);
4479             freeCardStatus(p_card_status);
4480             break;
4481         }
4482         case RIL_REQUEST_GET_CURRENT_CALLS:
4483             requestGetCurrentCalls(data, datalen, t);
4484             break;
4485         case RIL_REQUEST_DIAL:
4486             requestDial(data, datalen, t);
4487             break;
4488         case RIL_REQUEST_HANGUP:
4489             requestHangup(data, datalen, t);
4490             break;
4491         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
4492         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
4493         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
4494         case RIL_REQUEST_CONFERENCE:
4495         case RIL_REQUEST_UDUB:
4496              requestCallSelection(data, datalen, t, request);
4497              break;
4498         case RIL_REQUEST_ANSWER:
4499             at_send_command("ATA", NULL);
4500 
4501 #ifdef WORKAROUND_ERRONEOUS_ANSWER
4502             s_expectAnswer = 1;
4503 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
4504 
4505             if (getSIMStatus() != SIM_READY) {
4506                 RIL_onRequestComplete(t, RIL_E_MODEM_ERR, NULL, 0);
4507             } else {
4508                 // Success or failure is ignored by the upper layer here.
4509                 // It will call GET_CURRENT_CALLS and determine success that way.
4510                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4511             }
4512             break;
4513 
4514         case RIL_REQUEST_SEPARATE_CONNECTION:
4515             {
4516                 char  cmd[12];
4517                 int   party = ((int*)data)[0];
4518 
4519                 if (getSIMStatus() == SIM_ABSENT) {
4520                     RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
4521                     return;
4522                 }
4523                 // Make sure that party is in a valid range.
4524                 // (Note: The Telephony middle layer imposes a range of 1 to 7.
4525                 // It's sufficient for us to just make sure it's single digit.)
4526                 if (party > 0 && party < 10) {
4527                     sprintf(cmd, "AT+CHLD=2%d", party);
4528                     at_send_command(cmd, NULL);
4529                     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4530                 } else {
4531                     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4532                 }
4533             }
4534             break;
4535 
4536         case RIL_REQUEST_SIGNAL_STRENGTH:
4537             requestSignalStrength(data, datalen, t);
4538             break;
4539         case RIL_REQUEST_VOICE_REGISTRATION_STATE:
4540         case RIL_REQUEST_DATA_REGISTRATION_STATE:
4541             requestRegistrationState(request, data, datalen, t);
4542             break;
4543         case RIL_REQUEST_OPERATOR:
4544             requestOperator(data, datalen, t);
4545             break;
4546         case RIL_REQUEST_RADIO_POWER:
4547             requestRadioPower(data, datalen, t);
4548             break;
4549         case RIL_REQUEST_DTMF: {
4550             char c = ((char *)data)[0];
4551             char *cmd;
4552             asprintf(&cmd, "AT+VTS=%c", (int)c);
4553             at_send_command(cmd, NULL);
4554             free(cmd);
4555             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4556             break;
4557         }
4558         case RIL_REQUEST_SEND_SMS:
4559         case RIL_REQUEST_SEND_SMS_EXPECT_MORE:
4560             requestSendSMS(data, datalen, t);
4561             break;
4562         case RIL_REQUEST_CDMA_SEND_SMS:
4563             requestCdmaSendSMS(data, datalen, t);
4564             break;
4565         case RIL_REQUEST_IMS_SEND_SMS:
4566             requestImsSendSMS(data, datalen, t);
4567             break;
4568         case RIL_REQUEST_SIM_OPEN_CHANNEL:
4569             requestSimOpenChannel(data, datalen, t);
4570             break;
4571         case RIL_REQUEST_SIM_CLOSE_CHANNEL:
4572             requestSimCloseChannel(data, datalen, t);
4573             break;
4574         case RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL:
4575             requestSimTransmitApduChannel(data, datalen, t);
4576             break;
4577         case RIL_REQUEST_SIM_AUTHENTICATION: {
4578             RIL_SimAuthentication *sim_auth = (RIL_SimAuthentication *)data;
4579             if ((sim_auth->authContext == AUTH_CONTEXT_EAP_SIM ||
4580                  sim_auth->authContext == AUTH_CONTEXT_EAP_AKA) &&
4581                 sim_auth->authData != NULL) {
4582                 requestSimAuthentication(sim_auth->authContext, sim_auth->authData, t);
4583             } else {
4584                 RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
4585             }
4586             break;
4587         }
4588         case RIL_REQUEST_SIM_TRANSMIT_APDU_BASIC:
4589             requestTransmitApduBasic(data, datalen, t);
4590             break;
4591         case RIL_REQUEST_SETUP_DATA_CALL:
4592             requestSetupDataCall(data, datalen, t);
4593             break;
4594         case RIL_REQUEST_DEACTIVATE_DATA_CALL:
4595             requestDeactivateDataCall(data, t);
4596             break;
4597         case RIL_REQUEST_SMS_ACKNOWLEDGE:
4598             requestSMSAcknowledge(data, datalen, t);
4599             break;
4600 
4601         case RIL_REQUEST_GET_IMSI:
4602             p_response = NULL;
4603             err = at_send_command_numeric("AT+CIMI", &p_response);
4604 
4605             if (err < 0 || p_response->success == 0) {
4606                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4607             } else {
4608                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
4609                     p_response->p_intermediates->line, sizeof(char *));
4610             }
4611             at_response_free(p_response);
4612             break;
4613 
4614         case RIL_REQUEST_GET_IMEI:
4615             p_response = NULL;
4616             err = at_send_command_numeric("AT+CGSN", &p_response);
4617 
4618             if (err < 0 || p_response->success == 0) {
4619                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4620             } else {
4621                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
4622                     p_response->p_intermediates->line, sizeof(char *));
4623             }
4624             at_response_free(p_response);
4625             break;
4626 
4627 
4628         case RIL_REQUEST_SIM_IO:
4629             requestSIM_IO(data,datalen,t);
4630             break;
4631 
4632         case RIL_REQUEST_SEND_USSD:
4633             requestSendUSSD(data, datalen, t);
4634             break;
4635 
4636         case RIL_REQUEST_CANCEL_USSD:
4637             if (getSIMStatus() == SIM_ABSENT) {
4638                 RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
4639                 break;
4640             }
4641             p_response = NULL;
4642             err = at_send_command_numeric("AT+CUSD=2", &p_response);
4643 
4644             if (err < 0 || p_response->success == 0) {
4645                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4646             } else {
4647                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
4648                     p_response->p_intermediates->line, sizeof(char *));
4649             }
4650             at_response_free(p_response);
4651             break;
4652 
4653         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
4654             if (getSIMStatus() == SIM_ABSENT) {
4655                 RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
4656                 break;
4657             }
4658             p_response = NULL;
4659             err = at_send_command("AT+COPS=0", &p_response);
4660             if (err < 0 || p_response->success == 0) {
4661                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4662             } else {
4663                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4664             }
4665             at_response_free(p_response);
4666             break;
4667 
4668         case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL:
4669             requestSetNetworlSelectionManual(data, t);
4670             break;
4671 
4672         case RIL_REQUEST_DATA_CALL_LIST:
4673             requestDataCallList(data, datalen, t);
4674             break;
4675 
4676         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
4677             requestQueryNetworkSelectionMode(data, datalen, t);
4678             break;
4679 
4680         case RIL_REQUEST_OEM_HOOK_RAW:
4681             // echo back data
4682             RIL_onRequestComplete(t, RIL_E_SUCCESS, data, datalen);
4683             break;
4684 
4685 
4686         case RIL_REQUEST_OEM_HOOK_STRINGS: {
4687             int i;
4688             const char ** cur;
4689 
4690             RLOGD("got OEM_HOOK_STRINGS: 0x%8p %lu", data, (long)datalen);
4691 
4692 
4693             for (i = (datalen / sizeof (char *)), cur = (const char **)data ;
4694                     i > 0 ; cur++, i --) {
4695                 RLOGD("> '%s'", *cur);
4696             }
4697 
4698             // echo back strings
4699             RIL_onRequestComplete(t, RIL_E_SUCCESS, data, datalen);
4700             break;
4701         }
4702 
4703         case RIL_REQUEST_WRITE_SMS_TO_SIM:
4704             requestWriteSmsToSim(data, datalen, t);
4705             break;
4706 
4707         case RIL_REQUEST_DELETE_SMS_ON_SIM: {
4708             char * cmd;
4709             p_response = NULL;
4710             asprintf(&cmd, "AT+CMGD=%d", ((int *)data)[0]);
4711             err = at_send_command(cmd, &p_response);
4712             free(cmd);
4713             if (err < 0 || p_response->success == 0) {
4714                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4715             } else {
4716                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4717             }
4718             at_response_free(p_response);
4719             break;
4720         }
4721 
4722         case RIL_REQUEST_ENTER_SIM_PIN:
4723         case RIL_REQUEST_ENTER_SIM_PIN2:
4724             requestEnterSimPin(request, data, datalen, t);
4725             break;
4726 
4727         case RIL_REQUEST_ENTER_SIM_PUK:
4728         case RIL_REQUEST_ENTER_SIM_PUK2:
4729         case RIL_REQUEST_CHANGE_SIM_PIN:
4730             requestChangeSimPin(request, data, datalen, t);
4731             break;
4732 
4733         case RIL_REQUEST_CHANGE_SIM_PIN2:
4734             requestChangeSimPin2(data, datalen, t);
4735             break;
4736 
4737         case RIL_REQUEST_IMS_REGISTRATION_STATE: {
4738             int reply[2];
4739             //0==unregistered, 1==registered
4740             reply[0] = s_ims_registered;
4741 
4742             //to be used when changed to include service supporated info
4743             //reply[1] = s_ims_services;
4744 
4745             // FORMAT_3GPP(1) vs FORMAT_3GPP2(2);
4746             reply[1] = s_ims_format;
4747 
4748             RLOGD("IMS_REGISTRATION=%d, format=%d ",
4749                     reply[0], reply[1]);
4750             if (reply[1] != -1) {
4751                 RIL_onRequestComplete(t, RIL_E_SUCCESS, reply, sizeof(reply));
4752             } else {
4753                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4754             }
4755             break;
4756         }
4757 
4758         case RIL_REQUEST_VOICE_RADIO_TECH:
4759             {
4760                 int tech = techFromModemType(TECH(sMdmInfo));
4761                 if (tech < 0 )
4762                     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
4763                 else
4764                     RIL_onRequestComplete(t, RIL_E_SUCCESS, &tech, sizeof(tech));
4765             }
4766             break;
4767         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
4768             requestSetPreferredNetworkType(request, data, datalen, t);
4769             break;
4770 
4771         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
4772             requestGetPreferredNetworkType(request, data, datalen, t);
4773             break;
4774 
4775         case RIL_REQUEST_GET_CELL_INFO_LIST:
4776             requestGetCellInfoList(data, datalen, t);
4777             break;
4778 
4779         case RIL_REQUEST_GET_CELL_INFO_LIST_1_6:
4780             requestGetCellInfoList_1_6(data, datalen, t);
4781             break;
4782 
4783         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
4784             requestSetCellInfoListRate(data, datalen, t);
4785             break;
4786 
4787         case RIL_REQUEST_GET_HARDWARE_CONFIG:
4788             requestGetHardwareConfig(data, datalen, t);
4789             break;
4790 
4791         case RIL_REQUEST_SHUTDOWN:
4792             requestShutdown(t);
4793             break;
4794 
4795         case RIL_REQUEST_QUERY_TTY_MODE:
4796             requestGetTtyMode(data, datalen, t);
4797             break;
4798 
4799         case RIL_REQUEST_GET_RADIO_CAPABILITY:
4800             requestGetRadioCapability(data, datalen, t);
4801             break;
4802 
4803         case RIL_REQUEST_SET_RADIO_CAPABILITY:
4804             requestSetRadioCapability(data, datalen, t);
4805             break;
4806 
4807         case RIL_REQUEST_GET_MUTE:
4808             requestGetMute(data, datalen, t);
4809             break;
4810 
4811         case RIL_REQUEST_SET_MUTE:
4812             requestSetMute(data, datalen, t);
4813             break;
4814 
4815         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: {
4816           int size = 5;
4817           int response[20] = {0};
4818           for (int i = 1; i <= size; i++) {
4819             response[i] = i - 1;
4820           }
4821           RIL_onRequestComplete(t, RIL_E_SUCCESS, response, (size + 1) * sizeof(int));
4822           break;
4823         }
4824 
4825         case RIL_REQUEST_SET_INITIAL_ATTACH_APN:
4826         case RIL_REQUEST_ALLOW_DATA:
4827         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION:
4828         case RIL_REQUEST_SET_BAND_MODE:
4829         case RIL_REQUEST_SET_CARRIER_RESTRICTIONS:
4830         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
4831         case RIL_REQUEST_SET_LOCATION_UPDATES:
4832         case RIL_REQUEST_SET_TTY_MODE:
4833         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:
4834             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4835             break;
4836 
4837         case RIL_REQUEST_NV_RESET_CONFIG:
4838             requestNvResetConfig(data, datalen, t);
4839             break;
4840 
4841         case RIL_REQUEST_BASEBAND_VERSION:
4842             requestCdmaBaseBandVersion(request, data, datalen, t);
4843             break;
4844 
4845         case RIL_REQUEST_DEVICE_IDENTITY:
4846             requestDeviceIdentity(request, data, datalen, t);
4847             break;
4848 
4849         case RIL_REQUEST_CDMA_SUBSCRIPTION:
4850             requestCdmaSubscription(request, data, datalen, t);
4851             break;
4852 
4853         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
4854             requestCdmaGetSubscriptionSource(request, data, datalen, t);
4855             break;
4856 
4857         case RIL_REQUEST_START_LCE:
4858         case RIL_REQUEST_STOP_LCE:
4859         case RIL_REQUEST_PULL_LCEDATA:
4860             if (getSIMStatus() == SIM_ABSENT) {
4861                 RIL_onRequestComplete(t, RIL_E_SIM_ABSENT, NULL, 0);
4862             } else {
4863                 RIL_onRequestComplete(t, RIL_E_LCE_NOT_SUPPORTED, NULL, 0);
4864             }
4865             break;
4866 
4867         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:
4868             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
4869                 requestCdmaGetRoamingPreference(request, data, datalen, t);
4870             } else {
4871                 RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
4872             }
4873             break;
4874 
4875         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
4876             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
4877                 requestCdmaSetSubscriptionSource(request, data, datalen, t);
4878             } else {
4879                 // VTS tests expect us to silently do nothing
4880                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4881             }
4882             break;
4883 
4884         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
4885             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
4886                 requestCdmaSetRoamingPreference(request, data, datalen, t);
4887             } else {
4888                 // VTS tests expect us to silently do nothing
4889                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4890             }
4891             break;
4892 
4893         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
4894             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
4895                 requestExitEmergencyMode(data, datalen, t);
4896             } else {
4897                 // VTS tests expect us to silently do nothing
4898                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4899             }
4900             break;
4901 
4902         case RIL_REQUEST_GET_ACTIVITY_INFO:
4903             requestGetActivityInfo(data, datalen, t);
4904             break;
4905 
4906         case RIL_REQUEST_SCREEN_STATE:
4907             requestScreenState(data, t);
4908             break;
4909 
4910         case RIL_REQUEST_SET_DATA_PROFILE:
4911             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4912             break;
4913 
4914         case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS:
4915             requestQueryCallForward(data, datalen, t);
4916             break;
4917 
4918         case RIL_REQUEST_SET_CALL_FORWARD:
4919             requestSetCallForward(data, datalen, t);
4920             break;
4921 
4922         case RIL_REQUEST_QUERY_CLIP:
4923             requestQueryClip(data, datalen, t);
4924             break;
4925 
4926         case RIL_REQUEST_GET_CLIR:
4927             requestQueryClir(data, datalen, t);
4928             break;
4929 
4930         case RIL_REQUEST_SET_CLIR:
4931             requestSetClir(data, datalen, t);
4932             break;
4933 
4934         case RIL_REQUEST_QUERY_CALL_WAITING:
4935             requestQueryCallWaiting(data, datalen, t);
4936             break;
4937 
4938         case RIL_REQUEST_SET_CALL_WAITING:
4939             requestSetCallWaiting(data, datalen, t);
4940             break;
4941 
4942         case RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION:
4943             requestSetSuppServiceNotifications(data, datalen, t);
4944             break;
4945 
4946         case RIL_REQUEST_CHANGE_BARRING_PASSWORD:
4947             requestChangeBarringPassword(data, datalen, t);
4948             break;
4949 
4950         case RIL_REQUEST_QUERY_FACILITY_LOCK: {
4951             char *lockData[4];
4952             lockData[0] = ((char **)data)[0];
4953             lockData[1] = "2";
4954             lockData[2] = ((char **)data)[1];
4955             lockData[3] = ((char **)data)[2];
4956             requestFacilityLock(request, lockData, datalen + sizeof(char *), t);
4957             break;
4958         }
4959 
4960         case RIL_REQUEST_SET_FACILITY_LOCK:
4961             requestFacilityLock(request, data, datalen, t);
4962             break;
4963 
4964         case RIL_REQUEST_GET_SMSC_ADDRESS:
4965             requestGetSmscAddress(data, datalen, t);
4966             break;
4967 
4968         case RIL_REQUEST_SET_SMSC_ADDRESS:
4969             requestSetSmscAddress(data, datalen, t);
4970             break;
4971 
4972         case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:
4973             requestSetSmsBroadcastConfig(data, datalen, t);
4974             break;
4975 
4976         case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:
4977             requestGetSmsBroadcastConfig(data, datalen, t);
4978             break;
4979 
4980         case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING:
4981             requestStkServiceIsRunning(t);
4982             break;
4983 
4984         case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND:
4985             requestStkSendEnvelope(data, t);
4986             break;
4987 
4988         case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE:
4989             requestStksendTerminalResponse(data, t);
4990             break;
4991 
4992         // New requests after P.
4993         case RIL_REQUEST_START_NETWORK_SCAN:
4994             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
4995             // send unsol network scan results after a short while
4996             RIL_requestTimedCallback (sendUnsolNetworkScanResult, NULL, &TIMEVAL_SIMPOLL);
4997             break;
4998         case RIL_REQUEST_GET_MODEM_STACK_STATUS:
4999             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5000             break;
5001         case RIL_REQUEST_ENABLE_MODEM:
5002             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5003             break;
5004         case RIL_REQUEST_EMERGENCY_DIAL:
5005             requestEccDial(data, t);
5006             break;
5007         case RIL_REQUEST_SET_SIM_CARD_POWER:
5008             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5009             break;
5010         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE_BITMAP:
5011             requestSetPreferredNetworkType(request, data, datalen, t);
5012             break;
5013         case RIL_REQUEST_SET_ALLOWED_NETWORK_TYPES_BITMAP:
5014             requestSetPreferredNetworkType(request, data, datalen, t);
5015             break;
5016         case RIL_REQUEST_GET_ALLOWED_NETWORK_TYPES_BITMAP:
5017             requestGetPreferredNetworkType(request, data, datalen, t);
5018         case RIL_REQUEST_ENABLE_NR_DUAL_CONNECTIVITY:
5019             if (data == NULL || datalen != sizeof(int)) {
5020                 RIL_onRequestComplete(t, RIL_E_INTERNAL_ERR, NULL, 0);
5021                 break;
5022             }
5023             int nrDualConnectivityState = *(int *)(data);
5024             isNrDualConnectivityEnabled = (nrDualConnectivityState == 1) ? true : false;
5025             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5026             break;
5027         case RIL_REQUEST_IS_NR_DUAL_CONNECTIVITY_ENABLED:
5028             RIL_onRequestComplete(t, RIL_E_SUCCESS, &isNrDualConnectivityEnabled,
5029                     sizeof(isNrDualConnectivityEnabled));
5030             break;
5031         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE_BITMAP:
5032             requestGetPreferredNetworkType(request, data, datalen, t);
5033             break;
5034         case RIL_REQUEST_SET_SYSTEM_SELECTION_CHANNELS:
5035             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5036             break;
5037         case RIL_REQUEST_GET_SLICING_CONFIG:
5038             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5039             break;
5040         case RIL_REQUEST_GET_CARRIER_RESTRICTIONS:
5041             requestGetCarrierRestrictions(data, datalen, t);
5042 
5043         // Radio config requests
5044         case RIL_REQUEST_CONFIG_GET_SLOT_STATUS:
5045             RIL_requestTimedCallback(onIccSlotStatus, (void *)t, NULL);
5046             break;
5047         case RIL_REQUEST_CONFIG_SET_SLOT_MAPPING:
5048             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5049             break;
5050         case RIL_REQUEST_CONFIG_GET_PHONE_CAPABILITY: {
5051             RIL_PhoneCapability *phoneCapability =
5052                     (RIL_PhoneCapability *)alloca(sizeof(RIL_PhoneCapability));
5053             phoneCapability->maxActiveData = 1;
5054             // DSDS is 1, and DSDA is 2, now only support DSDS
5055             phoneCapability->maxActiveInternetData = 1;
5056             // DSDA can support internet lingering
5057             phoneCapability->isInternetLingeringSupported = false;
5058             for (int num = 0; num < SIM_COUNT; num++) {
5059                 phoneCapability->logicalModemList[num].modemId = num;
5060             }
5061             RIL_onRequestComplete(t, RIL_E_SUCCESS,
5062                             phoneCapability, sizeof(RIL_PhoneCapability));
5063             break;
5064         }
5065         case RIL_REQUEST_CONFIG_SET_MODEM_CONFIG: {
5066             RIL_ModemConfig *mdConfig = (RIL_ModemConfig*)(data);
5067             if (mdConfig == NULL || mdConfig->numOfLiveModems != 1) {
5068                 RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
5069             } else {
5070                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5071             }
5072             break;
5073         }
5074         case RIL_REQUEST_CONFIG_GET_MODEM_CONFIG: {
5075             RIL_ModemConfig mdConfig;
5076             mdConfig.numOfLiveModems = 1;
5077 
5078             RIL_onRequestComplete(t, RIL_E_SUCCESS, &mdConfig, sizeof(RIL_ModemConfig));
5079             break;
5080         }
5081         case RIL_REQUEST_CONFIG_SET_PREFER_DATA_MODEM: {
5082             int *modemId = (int*)(data);
5083             if (modemId == NULL || *modemId != 0) {
5084                 RIL_onRequestComplete(t, RIL_E_INVALID_ARGUMENTS, NULL, 0);
5085             } else {
5086                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5087             }
5088             break;
5089         }
5090         case RIL_REQUEST_SET_SIGNAL_STRENGTH_REPORTING_CRITERIA:
5091             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5092             break;
5093         case RIL_REQUEST_SET_LINK_CAPACITY_REPORTING_CRITERIA:
5094             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5095             break;
5096         case RIL_REQUEST_ENABLE_UICC_APPLICATIONS: {
5097             if (data == NULL || datalen != sizeof(int)) {
5098                 RIL_onRequestComplete(t, RIL_E_INTERNAL_ERR, NULL, 0);
5099                 break;
5100             }
5101             areUiccApplicationsEnabled = *(int *)(data);
5102             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5103             break;
5104         }
5105         case RIL_REQUEST_ARE_UICC_APPLICATIONS_ENABLED:
5106             RIL_onRequestComplete(t, RIL_E_SUCCESS, &areUiccApplicationsEnabled,
5107                     sizeof(areUiccApplicationsEnabled));
5108             break;
5109         case RIL_REQUEST_CDMA_SEND_SMS_EXPECT_MORE:
5110             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5111             break;
5112         case RIL_REQUEST_GET_BARRING_INFO:
5113             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5114             break;
5115         case RIL_REQUEST_SET_DATA_THROTTLING:
5116             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5117             break;
5118         case RIL_REQUEST_START_KEEPALIVE:
5119             requestStartKeepalive(t);
5120             break;
5121         case RIL_REQUEST_STOP_KEEPALIVE:
5122             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5123             break;
5124         case RIL_REQUEST_SET_UNSOLICITED_RESPONSE_FILTER:
5125             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
5126             break;
5127         default:
5128             RLOGD("Request not supported. Tech: %d",TECH(sMdmInfo));
5129             RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
5130             break;
5131     }
5132 }
5133 
5134 /**
5135  * Synchronous call from the RIL to us to return current radio state.
5136  * RADIO_STATE_UNAVAILABLE should be the initial state.
5137  */
5138 static RIL_RadioState
5139 currentState()
5140 {
5141     return sState;
5142 }
5143 /**
5144  * Call from RIL to us to find out whether a specific request code
5145  * is supported by this implementation.
5146  *
5147  * Return 1 for "supported" and 0 for "unsupported"
5148  */
5149 
5150 static int
5151 onSupports (int requestCode __unused)
5152 {
5153     //@@@ todo
5154 
5155     return 1;
5156 }
5157 
5158 static void onCancel (RIL_Token t __unused)
5159 {
5160     //@@@todo
5161 
5162 }
5163 
5164 static const char * getVersion(void)
5165 {
5166     return "android reference-ril 1.0";
5167 }
5168 
5169 static void
5170 setRadioTechnology(ModemInfo *mdm, int newtech)
5171 {
5172     RLOGD("setRadioTechnology(%d)", newtech);
5173 
5174     int oldtech = TECH(mdm);
5175 
5176     if (newtech != oldtech) {
5177         RLOGD("Tech change (%d => %d)", oldtech, newtech);
5178         TECH(mdm) = newtech;
5179         if (techFromModemType(newtech) != techFromModemType(oldtech)) {
5180             int tech = techFromModemType(TECH(sMdmInfo));
5181             if (tech > 0 ) {
5182                 RIL_onUnsolicitedResponse(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
5183                                           &tech, sizeof(tech));
5184             }
5185         }
5186     }
5187 }
5188 
5189 static void
5190 setRadioState(RIL_RadioState newState)
5191 {
5192     RLOGD("setRadioState(%d)", newState);
5193     RIL_RadioState oldState;
5194 
5195     pthread_mutex_lock(&s_state_mutex);
5196 
5197     oldState = sState;
5198 
5199     if (s_closed > 0) {
5200         // If we're closed, the only reasonable state is
5201         // RADIO_STATE_UNAVAILABLE
5202         // This is here because things on the main thread
5203         // may attempt to change the radio state after the closed
5204         // event happened in another thread
5205         newState = RADIO_STATE_UNAVAILABLE;
5206     }
5207 
5208     if (sState != newState || s_closed > 0) {
5209         sState = newState;
5210 
5211         pthread_cond_broadcast (&s_state_cond);
5212     }
5213 
5214     pthread_mutex_unlock(&s_state_mutex);
5215 
5216 
5217     /* do these outside of the mutex */
5218     if (sState != oldState) {
5219         RIL_onUnsolicitedResponse (RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
5220                                     NULL, 0);
5221         // Sim state can change as result of radio state change
5222         RIL_onUnsolicitedResponse (RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED,
5223                                     NULL, 0);
5224 
5225         /* FIXME onSimReady() and onRadioPowerOn() cannot be called
5226          * from the AT reader thread
5227          * Currently, this doesn't happen, but if that changes then these
5228          * will need to be dispatched on the request thread
5229          */
5230         if (sState == RADIO_STATE_ON) {
5231             onRadioPowerOn();
5232         }
5233     }
5234 }
5235 
5236 /** Returns RUIM_NOT_READY on error */
5237 static SIM_Status
5238 getRUIMStatus()
5239 {
5240     ATResponse *p_response = NULL;
5241     int err;
5242     int ret;
5243     char *cpinLine;
5244     char *cpinResult;
5245 
5246     if (sState == RADIO_STATE_OFF || sState == RADIO_STATE_UNAVAILABLE) {
5247         ret = SIM_NOT_READY;
5248         goto done;
5249     }
5250 
5251     err = at_send_command_singleline("AT+CPIN?", "+CPIN:", &p_response);
5252 
5253     if (err != 0) {
5254         ret = SIM_NOT_READY;
5255         goto done;
5256     }
5257 
5258     switch (at_get_cme_error(p_response)) {
5259         case CME_SUCCESS:
5260             break;
5261 
5262         case CME_SIM_NOT_INSERTED:
5263             ret = SIM_ABSENT;
5264             goto done;
5265 
5266         default:
5267             ret = SIM_NOT_READY;
5268             goto done;
5269     }
5270 
5271     /* CPIN? has succeeded, now look at the result */
5272 
5273     cpinLine = p_response->p_intermediates->line;
5274     err = at_tok_start (&cpinLine);
5275 
5276     if (err < 0) {
5277         ret = SIM_NOT_READY;
5278         goto done;
5279     }
5280 
5281     err = at_tok_nextstr(&cpinLine, &cpinResult);
5282 
5283     if (err < 0) {
5284         ret = SIM_NOT_READY;
5285         goto done;
5286     }
5287 
5288     if (0 == strcmp (cpinResult, "SIM PIN")) {
5289         ret = SIM_PIN;
5290         goto done;
5291     } else if (0 == strcmp (cpinResult, "SIM PUK")) {
5292         ret = SIM_PUK;
5293         goto done;
5294     } else if (0 == strcmp (cpinResult, "PH-NET PIN")) {
5295         return SIM_NETWORK_PERSONALIZATION;
5296     } else if (0 != strcmp (cpinResult, "READY"))  {
5297         /* we're treating unsupported lock types as "sim absent" */
5298         ret = SIM_ABSENT;
5299         goto done;
5300     }
5301 
5302     at_response_free(p_response);
5303     p_response = NULL;
5304     cpinResult = NULL;
5305 
5306     ret = SIM_READY;
5307 
5308 done:
5309     at_response_free(p_response);
5310     return ret;
5311 }
5312 
5313 /** Returns SIM_NOT_READY on error */
5314 static SIM_Status
5315 getSIMStatus()
5316 {
5317     ATResponse *p_response = NULL;
5318     int err;
5319     int ret;
5320     char *cpinLine;
5321     char *cpinResult;
5322 
5323     RLOGD("getSIMStatus(). sState: %d",sState);
5324     err = at_send_command_singleline("AT+CPIN?", "+CPIN:", &p_response);
5325 
5326     if (err != 0) {
5327         ret = SIM_NOT_READY;
5328         goto done;
5329     }
5330 
5331     switch (at_get_cme_error(p_response)) {
5332         case CME_SUCCESS:
5333             break;
5334 
5335         case CME_SIM_NOT_INSERTED:
5336             ret = SIM_ABSENT;
5337             goto done;
5338 
5339         default:
5340             ret = SIM_NOT_READY;
5341             goto done;
5342     }
5343 
5344     /* CPIN? has succeeded, now look at the result */
5345 
5346     cpinLine = p_response->p_intermediates->line;
5347     err = at_tok_start (&cpinLine);
5348 
5349     if (err < 0) {
5350         ret = SIM_NOT_READY;
5351         goto done;
5352     }
5353 
5354     err = at_tok_nextstr(&cpinLine, &cpinResult);
5355 
5356     if (err < 0) {
5357         ret = SIM_NOT_READY;
5358         goto done;
5359     }
5360 
5361     if (0 == strcmp (cpinResult, "SIM PIN")) {
5362         ret = SIM_PIN;
5363         goto done;
5364     } else if (0 == strcmp (cpinResult, "SIM PUK")) {
5365         ret = SIM_PUK;
5366         goto done;
5367     } else if (0 == strcmp (cpinResult, "PH-NET PIN")) {
5368         return SIM_NETWORK_PERSONALIZATION;
5369     } else if (0 != strcmp (cpinResult, "READY"))  {
5370         /* we're treating unsupported lock types as "sim absent" */
5371         ret = SIM_ABSENT;
5372         goto done;
5373     }
5374 
5375     at_response_free(p_response);
5376     p_response = NULL;
5377     cpinResult = NULL;
5378 
5379     ret = (sState == RADIO_STATE_ON) ? SIM_READY : SIM_NOT_READY;
5380 
5381 done:
5382     at_response_free(p_response);
5383     return ret;
5384 }
5385 
5386 static void getIccId(char *iccid, int size) {
5387     int err = 0;
5388     ATResponse *p_response = NULL;
5389 
5390     if (iccid == NULL) {
5391         RLOGE("iccid buffer is null");
5392         return;
5393     }
5394     err = at_send_command_numeric("AT+CICCID", &p_response);
5395     if (err < 0 || p_response->success == 0) {
5396         goto error;
5397     }
5398 
5399     snprintf(iccid, size, "%s", p_response->p_intermediates->line);
5400 
5401 error:
5402     at_response_free(p_response);
5403 }
5404 
5405 /**
5406  * Get the current card status.
5407  *
5408  * This must be freed using freeCardStatus.
5409  * @return: On success returns RIL_E_SUCCESS
5410  */
5411 static int getCardStatus(RIL_CardStatus_v1_5 **pp_card_status) {
5412     static RIL_AppStatus app_status_array[] = {
5413         // SIM_ABSENT = 0
5414         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
5415           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5416         // SIM_NOT_READY = 1
5417         { RIL_APPTYPE_USIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
5418           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5419         // SIM_READY = 2
5420         { RIL_APPTYPE_USIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
5421           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5422         // SIM_PIN = 3
5423         { RIL_APPTYPE_USIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
5424           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
5425         // SIM_PUK = 4
5426         { RIL_APPTYPE_USIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
5427           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
5428         // SIM_NETWORK_PERSONALIZATION = 5
5429         { RIL_APPTYPE_USIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
5430           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
5431         // RUIM_ABSENT = 6
5432         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
5433           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5434         // RUIM_NOT_READY = 7
5435         { RIL_APPTYPE_RUIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
5436           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5437         // RUIM_READY = 8
5438         { RIL_APPTYPE_RUIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
5439           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5440         // RUIM_PIN = 9
5441         { RIL_APPTYPE_RUIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
5442           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
5443         // RUIM_PUK = 10
5444         { RIL_APPTYPE_RUIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
5445           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
5446         // RUIM_NETWORK_PERSONALIZATION = 11
5447         { RIL_APPTYPE_RUIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
5448            NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
5449         // ISIM_ABSENT = 12
5450         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
5451           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5452         // ISIM_NOT_READY = 13
5453         { RIL_APPTYPE_ISIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
5454           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5455         // ISIM_READY = 14
5456         { RIL_APPTYPE_ISIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
5457           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
5458         // ISIM_PIN = 15
5459         { RIL_APPTYPE_ISIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
5460           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
5461         // ISIM_PUK = 16
5462         { RIL_APPTYPE_ISIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
5463           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
5464         // ISIM_NETWORK_PERSONALIZATION = 17
5465         { RIL_APPTYPE_ISIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
5466           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
5467 
5468     };
5469     RIL_CardState card_state;
5470     int num_apps;
5471 
5472     int sim_status = getSIMStatus();
5473     if (sim_status == SIM_ABSENT) {
5474         card_state = RIL_CARDSTATE_ABSENT;
5475         num_apps = 0;
5476     } else {
5477         card_state = RIL_CARDSTATE_PRESENT;
5478         num_apps = 3;
5479     }
5480 
5481     // Allocate and initialize base card status.
5482     RIL_CardStatus_v1_5 *p_card_status = calloc(1, sizeof(RIL_CardStatus_v1_5));
5483     p_card_status->base.base.base.card_state = card_state;
5484     p_card_status->base.base.base.universal_pin_state = RIL_PINSTATE_UNKNOWN;
5485     p_card_status->base.base.base.gsm_umts_subscription_app_index = -1;
5486     p_card_status->base.base.base.cdma_subscription_app_index = -1;
5487     p_card_status->base.base.base.ims_subscription_app_index = -1;
5488     p_card_status->base.base.base.num_applications = num_apps;
5489     p_card_status->base.base.physicalSlotId = 0;
5490     p_card_status->base.base.atr = NULL;
5491     p_card_status->base.base.iccid = NULL;
5492     p_card_status->base.eid = "";
5493     if (sim_status != SIM_ABSENT) {
5494         p_card_status->base.base.iccid = (char *)calloc(64, sizeof(char));
5495         getIccId(p_card_status->base.base.iccid, 64);
5496     }
5497 
5498     // Initialize application status
5499     int i;
5500     for (i = 0; i < RIL_CARD_MAX_APPS; i++) {
5501         p_card_status->base.base.base.applications[i] = app_status_array[SIM_ABSENT];
5502     }
5503     RLOGD("enter getCardStatus module, num_apps= %d",num_apps);
5504     // Pickup the appropriate application status
5505     // that reflects sim_status for gsm.
5506     if (num_apps != 0) {
5507         p_card_status->base.base.base.num_applications = 3;
5508         p_card_status->base.base.base.gsm_umts_subscription_app_index = 0;
5509         p_card_status->base.base.base.cdma_subscription_app_index = 1;
5510         p_card_status->base.base.base.ims_subscription_app_index = 2;
5511 
5512         // Get the correct app status
5513         p_card_status->base.base.base.applications[0] = app_status_array[sim_status];
5514         p_card_status->base.base.base.applications[1] = app_status_array[sim_status + RUIM_ABSENT];
5515         p_card_status->base.base.base.applications[2] = app_status_array[sim_status + ISIM_ABSENT];
5516     }
5517 
5518     *pp_card_status = p_card_status;
5519     return RIL_E_SUCCESS;
5520 }
5521 
5522 /**
5523  * Free the card status returned by getCardStatus
5524  */
5525 static void freeCardStatus(RIL_CardStatus_v1_5 *p_card_status) {
5526     if (p_card_status == NULL) {
5527         return;
5528     }
5529     free(p_card_status->base.base.iccid);
5530     free(p_card_status);
5531 }
5532 
5533 /**
5534  * SIM ready means any commands that access the SIM will work, including:
5535  *  AT+CPIN, AT+CSMS, AT+CNMI, AT+CRSM
5536  *  (all SMS-related commands)
5537  */
5538 
5539 static void pollSIMState (void *param __unused)
5540 {
5541     ATResponse *p_response;
5542     int ret;
5543 
5544     if (sState != RADIO_STATE_UNAVAILABLE) {
5545         // no longer valid to poll
5546         return;
5547     }
5548 
5549     switch(getSIMStatus()) {
5550         case SIM_ABSENT:
5551         case SIM_PIN:
5552         case SIM_PUK:
5553         case SIM_NETWORK_PERSONALIZATION:
5554         default:
5555             RLOGI("SIM ABSENT or LOCKED");
5556             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
5557         return;
5558 
5559         case SIM_NOT_READY:
5560             RIL_requestTimedCallback (pollSIMState, NULL, &TIMEVAL_SIMPOLL);
5561         return;
5562 
5563         case SIM_READY:
5564             RLOGI("SIM_READY");
5565             onSIMReady();
5566             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
5567         return;
5568     }
5569 }
5570 
5571 /** returns 1 if on, 0 if off, and -1 on error */
5572 static int isRadioOn()
5573 {
5574     ATResponse *p_response = NULL;
5575     int err;
5576     char *line;
5577     char ret;
5578 
5579     err = at_send_command_singleline("AT+CFUN?", "+CFUN:", &p_response);
5580 
5581     if (err < 0 || p_response->success == 0) {
5582         // assume radio is off
5583         goto error;
5584     }
5585 
5586     line = p_response->p_intermediates->line;
5587 
5588     err = at_tok_start(&line);
5589     if (err < 0) goto error;
5590 
5591     err = at_tok_nextbool(&line, &ret);
5592     if (err < 0) goto error;
5593 
5594     at_response_free(p_response);
5595 
5596     return (int)ret;
5597 
5598 error:
5599 
5600     at_response_free(p_response);
5601     return -1;
5602 }
5603 
5604 /**
5605  * Parse the response generated by a +CTEC AT command
5606  * The values read from the response are stored in current and preferred.
5607  * Both current and preferred may be null. The corresponding value is ignored in that case.
5608  *
5609  * @return: -1 if some error occurs (or if the modem doesn't understand the +CTEC command)
5610  *          1 if the response includes the current technology only
5611  *          0 if the response includes both current technology and preferred mode
5612  */
5613 int parse_technology_response( const char *response, int *current, int32_t *preferred )
5614 {
5615     int err;
5616     char *line, *p;
5617     int ct;
5618     int32_t pt = 0;
5619     char *str_pt;
5620 
5621     line = p = strdup(response);
5622     RLOGD("Response: %s", line);
5623     err = at_tok_start(&p);
5624     if (err || !at_tok_hasmore(&p)) {
5625         RLOGD("err: %d. p: %s", err, p);
5626         free(line);
5627         return -1;
5628     }
5629 
5630     err = at_tok_nextint(&p, &ct);
5631     if (err) {
5632         free(line);
5633         return -1;
5634     }
5635     if (current) *current = ct;
5636 
5637     RLOGD("line remaining after int: %s", p);
5638 
5639     err = at_tok_nexthexint(&p, &pt);
5640     if (err) {
5641         free(line);
5642         return 1;
5643     }
5644     if (preferred) {
5645         *preferred = pt;
5646     }
5647     free(line);
5648 
5649     return 0;
5650 }
5651 
5652 int query_supported_techs( ModemInfo *mdm __unused, int *supported )
5653 {
5654     ATResponse *p_response;
5655     int err, val, techs = 0;
5656     char *tok;
5657     char *line;
5658 
5659     RLOGD("query_supported_techs");
5660     err = at_send_command_singleline("AT+CTEC=?", "+CTEC:", &p_response);
5661     if (err || !p_response->success)
5662         goto error;
5663     line = p_response->p_intermediates->line;
5664     err = at_tok_start(&line);
5665     if (err || !at_tok_hasmore(&line))
5666         goto error;
5667     while (!at_tok_nextint(&line, &val)) {
5668         techs |= ( 1 << val );
5669     }
5670     if (supported) *supported = techs;
5671     return 0;
5672 error:
5673     at_response_free(p_response);
5674     return -1;
5675 }
5676 
5677 /**
5678  * query_ctec. Send the +CTEC AT command to the modem to query the current
5679  * and preferred modes. It leaves values in the addresses pointed to by
5680  * current and preferred. If any of those pointers are NULL, the corresponding value
5681  * is ignored, but the return value will still reflect if retrieving and parsing of the
5682  * values succeeded.
5683  *
5684  * @mdm Currently unused
5685  * @current A pointer to store the current mode returned by the modem. May be null.
5686  * @preferred A pointer to store the preferred mode returned by the modem. May be null.
5687  * @return -1 on error (or failure to parse)
5688  *         1 if only the current mode was returned by modem (or failed to parse preferred)
5689  *         0 if both current and preferred were returned correctly
5690  */
5691 int query_ctec(ModemInfo *mdm __unused, int *current, int32_t *preferred)
5692 {
5693     ATResponse *response = NULL;
5694     int err;
5695     int res;
5696 
5697     RLOGD("query_ctec. current: %p, preferred: %p", current, preferred);
5698     err = at_send_command_singleline("AT+CTEC?", "+CTEC:", &response);
5699     if (!err && response->success) {
5700         res = parse_technology_response(response->p_intermediates->line, current, preferred);
5701         at_response_free(response);
5702         return res;
5703     }
5704     RLOGE("Error executing command: %d. response: %p. status: %d", err, response, response? response->success : -1);
5705     at_response_free(response);
5706     return -1;
5707 }
5708 
5709 int is_multimode_modem(ModemInfo *mdm)
5710 {
5711     ATResponse *response;
5712     int err;
5713     char *line;
5714     int tech;
5715     int32_t preferred;
5716 
5717     if (query_ctec(mdm, &tech, &preferred) == 0) {
5718         mdm->currentTech = tech;
5719         mdm->preferredNetworkMode = preferred;
5720         if (query_supported_techs(mdm, &mdm->supportedTechs)) {
5721             return 0;
5722         }
5723         return 1;
5724     }
5725     return 0;
5726 }
5727 
5728 /**
5729  * Find out if our modem is GSM, CDMA or both (Multimode)
5730  */
5731 static void probeForModemMode(ModemInfo *info)
5732 {
5733     ATResponse *response;
5734     int err;
5735     assert (info);
5736     // Currently, our only known multimode modem is qemu's android modem,
5737     // which implements the AT+CTEC command to query and set mode.
5738     // Try that first
5739 
5740     if (is_multimode_modem(info)) {
5741         RLOGI("Found Multimode Modem. Supported techs mask: %8.8x. Current tech: %d",
5742             info->supportedTechs, info->currentTech);
5743         return;
5744     }
5745 
5746     /* Being here means that our modem is not multimode */
5747     info->isMultimode = 0;
5748 
5749     /* CDMA Modems implement the AT+WNAM command */
5750     err = at_send_command_singleline("AT+WNAM","+WNAM:", &response);
5751     if (!err && response->success) {
5752         at_response_free(response);
5753         // TODO: find out if we really support EvDo
5754         info->supportedTechs = MDM_CDMA | MDM_EVDO;
5755         info->currentTech = MDM_CDMA;
5756         RLOGI("Found CDMA Modem");
5757         return;
5758     }
5759     if (!err) at_response_free(response);
5760     // TODO: find out if modem really supports WCDMA/LTE
5761     info->supportedTechs = MDM_GSM | MDM_WCDMA | MDM_LTE;
5762     info->currentTech = MDM_GSM;
5763     RLOGI("Found GSM Modem");
5764 }
5765 
5766 /**
5767  * Initialize everything that can be configured while we're still in
5768  * AT+CFUN=0
5769  */
5770 static void initializeCallback(void *param __unused)
5771 {
5772     ATResponse *p_response = NULL;
5773     int err;
5774 
5775     setRadioState (RADIO_STATE_OFF);
5776 
5777     at_handshake();
5778 
5779     probeForModemMode(sMdmInfo);
5780     /* note: we don't check errors here. Everything important will
5781        be handled in onATTimeout and onATReaderClosed */
5782 
5783     /*  atchannel is tolerant of echo but it must */
5784     /*  have verbose result codes */
5785     at_send_command("ATE0Q0V1", NULL);
5786 
5787     /*  No auto-answer */
5788     at_send_command("ATS0=0", NULL);
5789 
5790     /*  Extended errors */
5791     at_send_command("AT+CMEE=1", NULL);
5792 
5793     /*  Network registration events */
5794     err = at_send_command("AT+CREG=2", &p_response);
5795 
5796     /* some handsets -- in tethered mode -- don't support CREG=2 */
5797     if (err < 0 || p_response->success == 0) {
5798         at_send_command("AT+CREG=1", NULL);
5799     }
5800 
5801     at_response_free(p_response);
5802 
5803     /*  GPRS registration events */
5804     at_send_command("AT+CGREG=1", NULL);
5805 
5806     /*  Call Waiting notifications */
5807     at_send_command("AT+CCWA=1", NULL);
5808 
5809     /*  Alternating voice/data off */
5810     at_send_command("AT+CMOD=0", NULL);
5811 
5812     /*  Not muted */
5813     at_send_command("AT+CMUT=0", NULL);
5814 
5815     /*  +CSSU unsolicited supp service notifications */
5816     at_send_command("AT+CSSN=0,1", NULL);
5817 
5818     /*  no connected line identification */
5819     at_send_command("AT+COLP=0", NULL);
5820 
5821     /*  HEX character set */
5822     at_send_command("AT+CSCS=\"HEX\"", NULL);
5823 
5824     /*  USSD unsolicited */
5825     at_send_command("AT+CUSD=1", NULL);
5826 
5827     /*  Enable +CGEV GPRS event notifications, but don't buffer */
5828     at_send_command("AT+CGEREP=1,0", NULL);
5829 
5830     /*  SMS PDU mode */
5831     at_send_command("AT+CMGF=0", NULL);
5832 
5833 #ifdef USE_TI_COMMANDS
5834 
5835     at_send_command("AT%CPI=3", NULL);
5836 
5837     /*  TI specific -- notifications when SMS is ready (currently ignored) */
5838     at_send_command("AT%CSTAT=1", NULL);
5839 
5840 #endif /* USE_TI_COMMANDS */
5841 
5842 
5843     /* assume radio is off on error */
5844     if (isRadioOn() > 0) {
5845         setRadioState (RADIO_STATE_ON);
5846     }
5847 }
5848 
5849 static void waitForClose()
5850 {
5851     pthread_mutex_lock(&s_state_mutex);
5852 
5853     while (s_closed == 0) {
5854         pthread_cond_wait(&s_state_cond, &s_state_mutex);
5855     }
5856 
5857     pthread_mutex_unlock(&s_state_mutex);
5858 }
5859 
5860 static void sendUnsolImsNetworkStateChanged()
5861 {
5862 #if 0 // to be used when unsol is changed to return data.
5863     int reply[2];
5864     reply[0] = s_ims_registered;
5865     reply[1] = s_ims_services;
5866     reply[1] = s_ims_format;
5867 #endif
5868     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED,
5869             NULL, 0);
5870 }
5871 
5872 static int parseProactiveCmdInd(char *response) {
5873     int typePos = 0;
5874     int cmdType = 0;
5875     char tempStr[3] = {0};
5876     char *end = NULL;
5877     StkUnsolEvent ret = STK_UNSOL_EVENT_UNKNOWN;
5878 
5879     if (response == NULL || strlen(response) < 3) {
5880       return ret;
5881     }
5882 
5883     if (response[2] <= '7') {
5884        typePos = 10;
5885     } else {
5886        typePos = 12;
5887     }
5888 
5889     if ((int)strlen(response) < typePos + 1) {
5890       return ret;
5891     }
5892 
5893     memcpy(tempStr, &(response[typePos]), 2);
5894     cmdType = strtoul(tempStr, &end, 16);
5895     cmdType = 0xFF & cmdType;
5896     RLOGD("cmdType: %d",cmdType);
5897 
5898     switch (cmdType) {
5899        case STK_RUN_AT:
5900        case STK_SEND_DTMF:
5901        case STK_SEND_SMS:
5902        case STK_SEND_SS:
5903        case STK_SEND_USSD:
5904        case STK_PLAY_TONE:
5905        case STK_CLOSE_CHANNEL:
5906            ret = STK_UNSOL_EVENT_NOTIFY;
5907            break;
5908        case STK_REFRESH:
5909            if (strncasecmp(&(response[typePos + 2]), "04", 2) == 0) {  // SIM_RESET
5910                RLOGD("Type of Refresh is SIM_RESET");
5911                s_stkServiceRunning = false;
5912                ret = STK_UNSOL_PROACTIVE_CMD;
5913            } else {
5914                ret = STK_UNSOL_EVENT_NOTIFY;
5915            }
5916            break;
5917        default:
5918            ret = STK_UNSOL_PROACTIVE_CMD;
5919            break;
5920     }
5921 
5922     if (getSIMStatus() == SIM_ABSENT && s_stkServiceRunning) {
5923         s_stkServiceRunning = false;
5924     }
5925 
5926     if (false == s_stkServiceRunning) {
5927         ret = STK_UNSOL_EVENT_UNKNOWN;
5928         s_stkUnsolResponse = (char *)calloc((strlen(response) + 1), sizeof(char));
5929         snprintf(s_stkUnsolResponse, strlen(response) + 1, "%s", response);
5930         RLOGD("STK service is not running [%s]", s_stkUnsolResponse);
5931     }
5932 
5933     return ret;
5934 }
5935 
5936 /**
5937  * Called by atchannel when an unsolicited line appears
5938  * This is called on atchannel's reader thread. AT commands may
5939  * not be issued here
5940  */
5941 static void onUnsolicited (const char *s, const char *sms_pdu)
5942 {
5943     char *line = NULL, *p;
5944     int err;
5945 
5946     /* Ignore unsolicited responses until we're initialized.
5947      * This is OK because the RIL library will poll for initial state
5948      */
5949     if (sState == RADIO_STATE_UNAVAILABLE) {
5950         return;
5951     }
5952 
5953 #define  CGFPCCFG "%CGFPCCFG:"
5954     if (strStartsWith(s, CGFPCCFG)) {
5955         /* cuttlefish/goldfish specific
5956         */
5957         char *response;
5958         line = p = strdup(s);
5959         RLOGD("got CGFPCCFG line %s and %s\n", s, p);
5960         err = at_tok_start(&line);
5961         if(err) {
5962             RLOGE("invalid CGFPCCFG line %s and %s\n", s, p);
5963         }
5964 #define kSize 5
5965         int configs[kSize];
5966         for (int i=0; i < kSize && !err; ++i) {
5967             err = at_tok_nextint(&line, &(configs[i]));
5968             RLOGD("got i %d, val = %d", i, configs[i]);
5969         }
5970         if(err) {
5971             RLOGE("invalid CGFPCCFG line %s and %s\n", s, p);
5972         } else {
5973             int modem_tech = configs[2];
5974             configs[2] = techFromModemType(modem_tech);
5975             RIL_onUnsolicitedResponse (
5976                 RIL_UNSOL_PHYSICAL_CHANNEL_CONFIGS,
5977                 configs, kSize);
5978         }
5979         free(p);
5980     } else if (strStartsWith(s, "%CTZV:")) {
5981         /* TI specific -- NITZ time */
5982         char *response;
5983 
5984         line = p = strdup(s);
5985         at_tok_start(&p);
5986 
5987         err = at_tok_nextstr(&p, &response);
5988 
5989         if (err != 0) {
5990             RLOGE("invalid NITZ line %s\n", s);
5991         } else {
5992             RIL_onUnsolicitedResponse (
5993                 RIL_UNSOL_NITZ_TIME_RECEIVED,
5994                 response, strlen(response) + 1);
5995         }
5996         free(line);
5997     } else if (strStartsWith(s,"+CRING:")
5998                 || strStartsWith(s,"RING")
5999                 || strStartsWith(s,"NO CARRIER")
6000                 || strStartsWith(s,"+CCWA")
6001     ) {
6002         RIL_onUnsolicitedResponse (
6003             RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
6004             NULL, 0);
6005 #ifdef WORKAROUND_FAKE_CGEV
6006         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL); //TODO use new function
6007 #endif /* WORKAROUND_FAKE_CGEV */
6008     } else if (strStartsWith(s,"+CREG:")
6009                 || strStartsWith(s,"+CGREG:")
6010     ) {
6011         RIL_onUnsolicitedResponse (
6012             RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
6013             NULL, 0);
6014 #ifdef WORKAROUND_FAKE_CGEV
6015         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
6016 #endif /* WORKAROUND_FAKE_CGEV */
6017     } else if (strStartsWith(s, "+CMT:")) {
6018         RIL_onUnsolicitedResponse (
6019             RIL_UNSOL_RESPONSE_NEW_SMS,
6020             sms_pdu, strlen(sms_pdu));
6021     } else if (strStartsWith(s, "+CDS:")) {
6022         RIL_onUnsolicitedResponse (
6023             RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT,
6024             sms_pdu, strlen(sms_pdu));
6025     } else if (strStartsWith(s, "+CGEV:")) {
6026         /* Really, we can ignore NW CLASS and ME CLASS events here,
6027          * but right now we don't since extranous
6028          * RIL_UNSOL_DATA_CALL_LIST_CHANGED calls are tolerated
6029          */
6030         /* can't issue AT commands here -- call on main thread */
6031         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
6032 #ifdef WORKAROUND_FAKE_CGEV
6033     } else if (strStartsWith(s, "+CME ERROR: 150")) {
6034         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
6035 #endif /* WORKAROUND_FAKE_CGEV */
6036     } else if (strStartsWith(s, "+CTEC: ")) {
6037         int tech, mask;
6038         switch (parse_technology_response(s, &tech, NULL))
6039         {
6040             case -1: // no argument could be parsed.
6041                 RLOGE("invalid CTEC line %s\n", s);
6042                 break;
6043             case 1: // current mode correctly parsed
6044             case 0: // preferred mode correctly parsed
6045                 mask = 1 << tech;
6046                 if (mask != MDM_GSM && mask != MDM_CDMA &&
6047                      mask != MDM_WCDMA && mask != MDM_LTE) {
6048                     RLOGE("Unknown technology %d\n", tech);
6049                 } else {
6050                     setRadioTechnology(sMdmInfo, tech);
6051                 }
6052                 break;
6053         }
6054     } else if (strStartsWith(s, "+CCSS: ")) {
6055         int source = 0;
6056         line = p = strdup(s);
6057         if (!line) {
6058             RLOGE("+CCSS: Unable to allocate memory");
6059             return;
6060         }
6061         if (at_tok_start(&p) < 0) {
6062             free(line);
6063             return;
6064         }
6065         if (at_tok_nextint(&p, &source) < 0) {
6066             RLOGE("invalid +CCSS response: %s", line);
6067             free(line);
6068             return;
6069         }
6070         SSOURCE(sMdmInfo) = source;
6071         RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
6072                                   &source, sizeof(source));
6073         free(line);
6074     } else if (strStartsWith(s, "+WSOS: ")) {
6075         char state = 0;
6076         int unsol;
6077         line = p = strdup(s);
6078         if (!line) {
6079             RLOGE("+WSOS: Unable to allocate memory");
6080             return;
6081         }
6082         if (at_tok_start(&p) < 0) {
6083             free(line);
6084             return;
6085         }
6086         if (at_tok_nextbool(&p, &state) < 0) {
6087             RLOGE("invalid +WSOS response: %s", line);
6088             free(line);
6089             return;
6090         }
6091         free(line);
6092 
6093         unsol = state ?
6094                 RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE : RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE;
6095 
6096         RIL_onUnsolicitedResponse(unsol, NULL, 0);
6097 
6098     } else if (strStartsWith(s, "+WPRL: ")) {
6099         int version = -1;
6100         line = p = strdup(s);
6101         if (!line) {
6102             RLOGE("+WPRL: Unable to allocate memory");
6103             return;
6104         }
6105         if (at_tok_start(&p) < 0) {
6106             RLOGE("invalid +WPRL response: %s", s);
6107             free(line);
6108             return;
6109         }
6110         if (at_tok_nextint(&p, &version) < 0) {
6111             RLOGE("invalid +WPRL response: %s", s);
6112             free(line);
6113             return;
6114         }
6115         free(line);
6116         RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_PRL_CHANGED, &version, sizeof(version));
6117     } else if (strStartsWith(s, "+CFUN: 0")) {
6118         setRadioState(RADIO_STATE_OFF);
6119     } else if (strStartsWith(s, "+CSQ: ")) {
6120         // Accept a response that is at least v6, and up to v12
6121         int minNumOfElements=sizeof(RIL_SignalStrength_v6)/sizeof(int);
6122         int maxNumOfElements=sizeof(RIL_SignalStrength_v12)/sizeof(int);
6123         int response[maxNumOfElements];
6124         memset(response, 0, sizeof(response));
6125 
6126         line = p = strdup(s);
6127         at_tok_start(&p);
6128 
6129         for (int count = 0; count < maxNumOfElements; count++) {
6130             err = at_tok_nextint(&p, &(response[count]));
6131             if (err < 0 && count < minNumOfElements) {
6132               free(line);
6133               return;
6134             }
6135         }
6136 
6137         RIL_onUnsolicitedResponse(RIL_UNSOL_SIGNAL_STRENGTH,
6138             response, sizeof(response));
6139         free(line);
6140     } else if (strStartsWith(s, "+CUSATEND")) {  // session end
6141         RIL_onUnsolicitedResponse(RIL_UNSOL_STK_SESSION_END, NULL, 0);
6142     } else if (strStartsWith(s, "+CUSATP:")) {
6143         line = p = strdup(s);
6144         if (!line) {
6145             RLOGE("+CUSATP: Unable to allocate memory");
6146             return;
6147         }
6148         if (at_tok_start(&p) < 0) {
6149             RLOGE("invalid +CUSATP response: %s", s);
6150             free(line);
6151             return;
6152         }
6153 
6154         char *response = NULL;
6155         if (at_tok_nextstr(&p, &response) < 0) {
6156             RLOGE("%s fail", s);
6157             free(line);
6158             return;
6159         }
6160 
6161         StkUnsolEvent ret = parseProactiveCmdInd(response);
6162         if (ret == STK_UNSOL_EVENT_NOTIFY) {
6163             RIL_onUnsolicitedResponse(RIL_UNSOL_STK_EVENT_NOTIFY, response,
6164                                       strlen(response) + 1);
6165         } else if (ret == STK_UNSOL_PROACTIVE_CMD) {
6166             RIL_onUnsolicitedResponse(RIL_UNSOL_STK_PROACTIVE_COMMAND, response,
6167                                       strlen(response) + 1);
6168         }
6169 
6170         free(line);
6171     }
6172 }
6173 
6174 /* Called on command or reader thread */
6175 static void onATReaderClosed()
6176 {
6177     RLOGI("AT channel closed\n");
6178     at_close();
6179     s_closed = 1;
6180 
6181     setRadioState (RADIO_STATE_UNAVAILABLE);
6182 }
6183 
6184 /* Called on command thread */
6185 static void onATTimeout()
6186 {
6187     RLOGI("AT channel timeout; closing\n");
6188     at_close();
6189 
6190     s_closed = 1;
6191 
6192     /* FIXME cause a radio reset here */
6193 
6194     setRadioState (RADIO_STATE_UNAVAILABLE);
6195 }
6196 
6197 /* Called to pass hardware configuration information to telephony
6198  * framework.
6199  */
6200 static void setHardwareConfiguration(int num, RIL_HardwareConfig *cfg)
6201 {
6202    RIL_onUnsolicitedResponse(RIL_UNSOL_HARDWARE_CONFIG_CHANGED, cfg, num*sizeof(*cfg));
6203 }
6204 
6205 static void usage(char *s __unused)
6206 {
6207 #ifdef RIL_SHLIB
6208     fprintf(stderr, "reference-ril requires: -p <tcp port> or -d /dev/tty_device\n");
6209 #else
6210     fprintf(stderr, "usage: %s [-p <tcp port>] [-d /dev/tty_device]\n", s);
6211     exit(-1);
6212 #endif
6213 }
6214 
6215 static void *
6216 mainLoop(void *param __unused)
6217 {
6218     int fd;
6219     int ret;
6220 
6221     AT_DUMP("== ", "entering mainLoop()", -1 );
6222     at_set_on_reader_closed(onATReaderClosed);
6223     at_set_on_timeout(onATTimeout);
6224 
6225     for (;;) {
6226         fd = -1;
6227         while  (fd < 0) {
6228             if (isInEmulator()) {
6229                 fd = qemu_open_modem_port();
6230                 RLOGD("opening qemu_modem_port %d!", fd);
6231             } else if (s_port > 0) {
6232                 fd = socket_network_client("localhost", s_port, SOCK_STREAM);
6233             } else if (s_modem_simulator_port >= 0) {
6234               fd = socket(AF_VSOCK, SOCK_STREAM, 0);
6235               if (fd < 0) {
6236                  RLOGD("Can't create AF_VSOCK socket!");
6237                  continue;
6238               }
6239               struct sockaddr_vm sa;
6240               memset(&sa, 0, sizeof(struct sockaddr_vm));
6241               sa.svm_family = AF_VSOCK;
6242               sa.svm_cid = VMADDR_CID_HOST;
6243               sa.svm_port = s_modem_simulator_port;
6244 
6245               if (connect(fd, (struct sockaddr *)(&sa), sizeof(sa)) < 0) {
6246                   RLOGD("Can't connect to port:%ud, errno: %s",
6247                       s_modem_simulator_port, strerror(errno));
6248                   close(fd);
6249                   fd = -1;
6250                   continue;
6251               }
6252             } else if (s_device_socket) {
6253                 fd = socket_local_client(s_device_path,
6254                                          ANDROID_SOCKET_NAMESPACE_FILESYSTEM,
6255                                          SOCK_STREAM);
6256             } else if (s_device_path != NULL) {
6257                 fd = open (s_device_path, O_RDWR);
6258                 if ( fd >= 0 && !memcmp( s_device_path, "/dev/ttyS", 9 ) ) {
6259                     /* disable echo on serial ports */
6260                     struct termios  ios;
6261                     tcgetattr( fd, &ios );
6262                     ios.c_lflag = 0;  /* disable ECHO, ICANON, etc... */
6263                     tcsetattr( fd, TCSANOW, &ios );
6264                 }
6265             }
6266 
6267             if (fd < 0) {
6268                 perror ("opening AT interface. retrying...");
6269                 sleep(10);
6270                 /* never returns */
6271             }
6272         }
6273 
6274         s_closed = 0;
6275         ret = at_open(fd, onUnsolicited);
6276 
6277         if (ret < 0) {
6278             RLOGE ("AT error %d on at_open\n", ret);
6279             return 0;
6280         }
6281 
6282         RIL_requestTimedCallback(initializeCallback, NULL, &TIMEVAL_0);
6283 
6284         // Give initializeCallback a chance to dispatched, since
6285         // we don't presently have a cancellation mechanism
6286         sleep(1);
6287 
6288         waitForClose();
6289         RLOGI("Re-opening after close");
6290     }
6291 }
6292 
6293 #ifdef RIL_SHLIB
6294 
6295 pthread_t s_tid_mainloop;
6296 
6297 const RIL_RadioFunctions *RIL_Init(const struct RIL_Env *env, int argc, char **argv)
6298 {
6299     int ret;
6300     int fd = -1;
6301     int opt;
6302     pthread_attr_t attr;
6303 
6304     s_rilenv = env;
6305 
6306     RLOGD("RIL_Init");
6307     while ( -1 != (opt = getopt(argc, argv, "p:d:s:c:m:"))) {
6308         switch (opt) {
6309             case 'p':
6310                 s_port = atoi(optarg);
6311                 if (s_port == 0) {
6312                     usage(argv[0]);
6313                     return NULL;
6314                 }
6315                 RLOGI("Opening loopback port %d\n", s_port);
6316             break;
6317 
6318             case 'd':
6319                 s_device_path = optarg;
6320                 RLOGI("Opening tty device %s\n", s_device_path);
6321             break;
6322 
6323             case 's':
6324                 s_device_path   = optarg;
6325                 s_device_socket = 1;
6326                 RLOGI("Opening socket %s\n", s_device_path);
6327             break;
6328 
6329             case 'c':
6330                 RLOGI("Client id received %s\n", optarg);
6331             break;
6332 
6333             case 'm':
6334               s_modem_simulator_port = strtoul(optarg, NULL, 10);
6335               RLOGI("Opening modem simulator port %ud\n", s_modem_simulator_port);
6336             break;
6337 
6338             default:
6339                 usage(argv[0]);
6340                 return NULL;
6341         }
6342     }
6343 
6344     if (s_port < 0 && s_device_path == NULL && !isInEmulator() &&
6345         s_modem_simulator_port < 0) {
6346         usage(argv[0]);
6347         return NULL;
6348     }
6349 
6350     sMdmInfo = calloc(1, sizeof(ModemInfo));
6351     if (!sMdmInfo) {
6352         RLOGE("Unable to alloc memory for ModemInfo");
6353         return NULL;
6354     }
6355     pthread_attr_init (&attr);
6356     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6357     ret = pthread_create(&s_tid_mainloop, &attr, mainLoop, NULL);
6358     if (ret < 0) {
6359         RLOGE("pthread_create: %s:", strerror(errno));
6360         return NULL;
6361     }
6362 
6363     return &s_callbacks;
6364 }
6365 #else /* RIL_SHLIB */
6366 int main (int argc, char **argv)
6367 {
6368     int ret;
6369     int fd = -1;
6370     int opt;
6371 
6372     while ( -1 != (opt = getopt(argc, argv, "p:d:"))) {
6373         switch (opt) {
6374             case 'p':
6375                 s_port = atoi(optarg);
6376                 if (s_port == 0) {
6377                     usage(argv[0]);
6378                 }
6379                 RLOGI("Opening loopback port %d\n", s_port);
6380             break;
6381 
6382             case 'd':
6383                 s_device_path = optarg;
6384                 RLOGI("Opening tty device %s\n", s_device_path);
6385             break;
6386 
6387             case 's':
6388                 s_device_path   = optarg;
6389                 s_device_socket = 1;
6390                 RLOGI("Opening socket %s\n", s_device_path);
6391             break;
6392 
6393             default:
6394                 usage(argv[0]);
6395         }
6396     }
6397 
6398     if (s_port < 0 && s_device_path == NULL && !isInEmulator()) {
6399         usage(argv[0]);
6400     }
6401 
6402     RIL_register(&s_callbacks);
6403 
6404     mainLoop(NULL);
6405 
6406     return 0;
6407 }
6408 
6409 #endif /* RIL_SHLIB */
6410