OSDN Git Service

Merge "Fix VTS test case HidlHalGTest#RadioHidlTest.getIccCardStatus_32bit failed."
[android-x86/hardware-ril.git] / reference-ril / reference-ril.c
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 "misc.h"
35 #include <getopt.h>
36 #include <sys/socket.h>
37 #include <cutils/sockets.h>
38 #include <sys/system_properties.h>
39 #include <termios.h>
40 #include <system/qemu_pipe.h>
41
42 #include "ril.h"
43
44 #define LOG_TAG "RIL"
45 #include <utils/Log.h>
46
47 static void *noopRemoveWarning( void *a ) { return a; }
48 #define RIL_UNUSED_PARM(a) noopRemoveWarning((void *)&(a));
49
50 #define MAX_AT_RESPONSE 0x1000
51
52 /* pathname returned from RIL_REQUEST_SETUP_DATA_CALL / RIL_REQUEST_SETUP_DEFAULT_PDP */
53 #define PPP_TTY_PATH "eth0"
54
55 // Default MTU value
56 #define DEFAULT_MTU 1500
57
58 #ifdef USE_TI_COMMANDS
59
60 // Enable a workaround
61 // 1) Make incoming call, do not answer
62 // 2) Hangup remote end
63 // Expected: call should disappear from CLCC line
64 // Actual: Call shows as "ACTIVE" before disappearing
65 #define WORKAROUND_ERRONEOUS_ANSWER 1
66
67 // Some varients of the TI stack do not support the +CGEV unsolicited
68 // response. However, they seem to send an unsolicited +CME ERROR: 150
69 #define WORKAROUND_FAKE_CGEV 1
70 #endif
71
72 /* Modem Technology bits */
73 #define MDM_GSM         0x01
74 #define MDM_WCDMA       0x02
75 #define MDM_CDMA        0x04
76 #define MDM_EVDO        0x08
77 #define MDM_LTE         0x10
78
79 typedef struct {
80     int supportedTechs; // Bitmask of supported Modem Technology bits
81     int currentTech;    // Technology the modem is currently using (in the format used by modem)
82     int isMultimode;
83
84     // Preferred mode bitmask. This is actually 4 byte-sized bitmasks with different priority values,
85     // in which the byte number from LSB to MSB give the priority.
86     //
87     //          |MSB|   |   |LSB
88     // value:   |00 |00 |00 |00
89     // byte #:  |3  |2  |1  |0
90     //
91     // Higher byte order give higher priority. Thus, a value of 0x0000000f represents
92     // a preferred mode of GSM, WCDMA, CDMA, and EvDo in which all are equally preferrable, whereas
93     // 0x00000201 represents a mode with GSM and WCDMA, in which WCDMA is preferred over GSM
94     int32_t preferredNetworkMode;
95     int subscription_source;
96
97 } ModemInfo;
98
99 static ModemInfo *sMdmInfo;
100 // TECH returns the current technology in the format used by the modem.
101 // It can be used as an l-value
102 #define TECH(mdminfo)                 ((mdminfo)->currentTech)
103 // TECH_BIT returns the bitmask equivalent of the current tech
104 #define TECH_BIT(mdminfo)            (1 << ((mdminfo)->currentTech))
105 #define IS_MULTIMODE(mdminfo)         ((mdminfo)->isMultimode)
106 #define TECH_SUPPORTED(mdminfo, tech) ((mdminfo)->supportedTechs & (tech))
107 #define PREFERRED_NETWORK(mdminfo)    ((mdminfo)->preferredNetworkMode)
108 // CDMA Subscription Source
109 #define SSOURCE(mdminfo)              ((mdminfo)->subscription_source)
110
111 static int net2modem[] = {
112     MDM_GSM | MDM_WCDMA,                                 // 0  - GSM / WCDMA Pref
113     MDM_GSM,                                             // 1  - GSM only
114     MDM_WCDMA,                                           // 2  - WCDMA only
115     MDM_GSM | MDM_WCDMA,                                 // 3  - GSM / WCDMA Auto
116     MDM_CDMA | MDM_EVDO,                                 // 4  - CDMA / EvDo Auto
117     MDM_CDMA,                                            // 5  - CDMA only
118     MDM_EVDO,                                            // 6  - EvDo only
119     MDM_GSM | MDM_WCDMA | MDM_CDMA | MDM_EVDO,           // 7  - GSM/WCDMA, CDMA, EvDo
120     MDM_LTE | MDM_CDMA | MDM_EVDO,                       // 8  - LTE, CDMA and EvDo
121     MDM_LTE | MDM_GSM | MDM_WCDMA,                       // 9  - LTE, GSM/WCDMA
122     MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_GSM | MDM_WCDMA, // 10 - LTE, CDMA, EvDo, GSM/WCDMA
123     MDM_LTE,                                             // 11 - LTE only
124 };
125
126 static int32_t net2pmask[] = {
127     MDM_GSM | (MDM_WCDMA << 8),                          // 0  - GSM / WCDMA Pref
128     MDM_GSM,                                             // 1  - GSM only
129     MDM_WCDMA,                                           // 2  - WCDMA only
130     MDM_GSM | MDM_WCDMA,                                 // 3  - GSM / WCDMA Auto
131     MDM_CDMA | MDM_EVDO,                                 // 4  - CDMA / EvDo Auto
132     MDM_CDMA,                                            // 5  - CDMA only
133     MDM_EVDO,                                            // 6  - EvDo only
134     MDM_GSM | MDM_WCDMA | MDM_CDMA | MDM_EVDO,           // 7  - GSM/WCDMA, CDMA, EvDo
135     MDM_LTE | MDM_CDMA | MDM_EVDO,                       // 8  - LTE, CDMA and EvDo
136     MDM_LTE | MDM_GSM | MDM_WCDMA,                       // 9  - LTE, GSM/WCDMA
137     MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_GSM | MDM_WCDMA, // 10 - LTE, CDMA, EvDo, GSM/WCDMA
138     MDM_LTE,                                             // 11 - LTE only
139 };
140
141 static int is3gpp2(int radioTech) {
142     switch (radioTech) {
143         case RADIO_TECH_IS95A:
144         case RADIO_TECH_IS95B:
145         case RADIO_TECH_1xRTT:
146         case RADIO_TECH_EVDO_0:
147         case RADIO_TECH_EVDO_A:
148         case RADIO_TECH_EVDO_B:
149         case RADIO_TECH_EHRPD:
150             return 1;
151         default:
152             return 0;
153     }
154 }
155
156 typedef enum {
157     SIM_ABSENT = 0,
158     SIM_NOT_READY = 1,
159     SIM_READY = 2,
160     SIM_PIN = 3,
161     SIM_PUK = 4,
162     SIM_NETWORK_PERSONALIZATION = 5,
163     RUIM_ABSENT = 6,
164     RUIM_NOT_READY = 7,
165     RUIM_READY = 8,
166     RUIM_PIN = 9,
167     RUIM_PUK = 10,
168     RUIM_NETWORK_PERSONALIZATION = 11
169 } SIM_Status;
170
171 static void onRequest (int request, void *data, size_t datalen, RIL_Token t);
172 static RIL_RadioState currentState();
173 static int onSupports (int requestCode);
174 static void onCancel (RIL_Token t);
175 static const char *getVersion();
176 static int isRadioOn();
177 static SIM_Status getSIMStatus();
178 static int getCardStatus(RIL_CardStatus_v6 **pp_card_status);
179 static void freeCardStatus(RIL_CardStatus_v6 *p_card_status);
180 static void onDataCallListChanged(void *param);
181
182 extern const char * requestToString(int request);
183
184 /*** Static Variables ***/
185 static const RIL_RadioFunctions s_callbacks = {
186     RIL_VERSION,
187     onRequest,
188     currentState,
189     onSupports,
190     onCancel,
191     getVersion
192 };
193
194 #ifdef RIL_SHLIB
195 static const struct RIL_Env *s_rilenv;
196
197 #define RIL_onRequestComplete(t, e, response, responselen) s_rilenv->OnRequestComplete(t,e, response, responselen)
198 #define RIL_onUnsolicitedResponse(a,b,c) s_rilenv->OnUnsolicitedResponse(a,b,c)
199 #define RIL_requestTimedCallback(a,b,c) s_rilenv->RequestTimedCallback(a,b,c)
200 #endif
201
202 static RIL_RadioState sState = RADIO_STATE_UNAVAILABLE;
203
204 static pthread_mutex_t s_state_mutex = PTHREAD_MUTEX_INITIALIZER;
205 static pthread_cond_t s_state_cond = PTHREAD_COND_INITIALIZER;
206
207 static int s_port = -1;
208 static const char * s_device_path = NULL;
209 static int          s_device_socket = 0;
210
211 /* trigger change to this with s_state_cond */
212 static int s_closed = 0;
213
214 static int sFD;     /* file desc of AT channel */
215 static char sATBuffer[MAX_AT_RESPONSE+1];
216 static char *sATBufferCur = NULL;
217
218 static const struct timeval TIMEVAL_SIMPOLL = {1,0};
219 static const struct timeval TIMEVAL_CALLSTATEPOLL = {0,500000};
220 static const struct timeval TIMEVAL_0 = {0,0};
221
222 static int s_ims_registered  = 0;        // 0==unregistered
223 static int s_ims_services    = 1;        // & 0x1 == sms over ims supported
224 static int s_ims_format    = 1;          // FORMAT_3GPP(1) vs FORMAT_3GPP2(2);
225 static int s_ims_cause_retry = 0;        // 1==causes sms over ims to temp fail
226 static int s_ims_cause_perm_failure = 0; // 1==causes sms over ims to permanent fail
227 static int s_ims_gsm_retry   = 0;        // 1==causes sms over gsm to temp fail
228 static int s_ims_gsm_fail    = 0;        // 1==causes sms over gsm to permanent fail
229
230 #ifdef WORKAROUND_ERRONEOUS_ANSWER
231 // Max number of times we'll try to repoll when we think
232 // we have a AT+CLCC race condition
233 #define REPOLL_CALLS_COUNT_MAX 4
234
235 // Line index that was incoming or waiting at last poll, or -1 for none
236 static int s_incomingOrWaitingLine = -1;
237 // Number of times we've asked for a repoll of AT+CLCC
238 static int s_repollCallsCount = 0;
239 // Should we expect a call to be answered in the next CLCC?
240 static int s_expectAnswer = 0;
241 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
242
243
244 static int s_cell_info_rate_ms = INT_MAX;
245 static int s_mcc = 0;
246 static int s_mnc = 0;
247 static int s_lac = 0;
248 static int s_cid = 0;
249
250 static void pollSIMState (void *param);
251 static void setRadioState(RIL_RadioState newState);
252 static void setRadioTechnology(ModemInfo *mdm, int newtech);
253 static int query_ctec(ModemInfo *mdm, int *current, int32_t *preferred);
254 static int parse_technology_response(const char *response, int *current, int32_t *preferred);
255 static int techFromModemType(int mdmtype);
256
257 static int clccStateToRILState(int state, RIL_CallState *p_state)
258
259 {
260     switch(state) {
261         case 0: *p_state = RIL_CALL_ACTIVE;   return 0;
262         case 1: *p_state = RIL_CALL_HOLDING;  return 0;
263         case 2: *p_state = RIL_CALL_DIALING;  return 0;
264         case 3: *p_state = RIL_CALL_ALERTING; return 0;
265         case 4: *p_state = RIL_CALL_INCOMING; return 0;
266         case 5: *p_state = RIL_CALL_WAITING;  return 0;
267         default: return -1;
268     }
269 }
270
271 /**
272  * Note: directly modified line and has *p_call point directly into
273  * modified line
274  */
275 static int callFromCLCCLine(char *line, RIL_Call *p_call)
276 {
277         //+CLCC: 1,0,2,0,0,\"+18005551212\",145
278         //     index,isMT,state,mode,isMpty(,number,TOA)?
279
280     int err;
281     int state;
282     int mode;
283
284     err = at_tok_start(&line);
285     if (err < 0) goto error;
286
287     err = at_tok_nextint(&line, &(p_call->index));
288     if (err < 0) goto error;
289
290     err = at_tok_nextbool(&line, &(p_call->isMT));
291     if (err < 0) goto error;
292
293     err = at_tok_nextint(&line, &state);
294     if (err < 0) goto error;
295
296     err = clccStateToRILState(state, &(p_call->state));
297     if (err < 0) goto error;
298
299     err = at_tok_nextint(&line, &mode);
300     if (err < 0) goto error;
301
302     p_call->isVoice = (mode == 0);
303
304     err = at_tok_nextbool(&line, &(p_call->isMpty));
305     if (err < 0) goto error;
306
307     if (at_tok_hasmore(&line)) {
308         err = at_tok_nextstr(&line, &(p_call->number));
309
310         /* tolerate null here */
311         if (err < 0) return 0;
312
313         // Some lame implementations return strings
314         // like "NOT AVAILABLE" in the CLCC line
315         if (p_call->number != NULL
316             && 0 == strspn(p_call->number, "+0123456789")
317         ) {
318             p_call->number = NULL;
319         }
320
321         err = at_tok_nextint(&line, &p_call->toa);
322         if (err < 0) goto error;
323     }
324
325     p_call->uusInfo = NULL;
326
327     return 0;
328
329 error:
330     RLOGE("invalid CLCC line\n");
331     return -1;
332 }
333
334 static int parseSimResponseLine(char* line, RIL_SIM_IO_Response* response) {
335     int err;
336
337     err = at_tok_start(&line);
338     if (err < 0) return err;
339     err = at_tok_nextint(&line, &response->sw1);
340     if (err < 0) return err;
341     err = at_tok_nextint(&line, &response->sw2);
342     if (err < 0) return err;
343
344     if (at_tok_hasmore(&line)) {
345         err = at_tok_nextstr(&line, &response->simResponse);
346         if (err < 0) return err;
347     }
348     return 0;
349 }
350
351 /** do post-AT+CFUN=1 initialization */
352 static void onRadioPowerOn()
353 {
354 #ifdef USE_TI_COMMANDS
355     /*  Must be after CFUN=1 */
356     /*  TI specific -- notifications for CPHS things such */
357     /*  as CPHS message waiting indicator */
358
359     at_send_command("AT%CPHS=1", NULL);
360
361     /*  TI specific -- enable NITZ unsol notifs */
362     at_send_command("AT%CTZV=1", NULL);
363 #endif
364
365     pollSIMState(NULL);
366 }
367
368 /** do post- SIM ready initialization */
369 static void onSIMReady()
370 {
371     at_send_command_singleline("AT+CSMS=1", "+CSMS:", NULL);
372     /*
373      * Always send SMS messages directly to the TE
374      *
375      * mode = 1 // discard when link is reserved (link should never be
376      *             reserved)
377      * mt = 2   // most messages routed to TE
378      * bm = 2   // new cell BM's routed to TE
379      * ds = 1   // Status reports routed to TE
380      * bfr = 1  // flush buffer
381      */
382     at_send_command("AT+CNMI=1,2,2,1,1", NULL);
383 }
384
385 static void requestRadioPower(void *data, size_t datalen __unused, RIL_Token t)
386 {
387     int onOff;
388
389     int err;
390     ATResponse *p_response = NULL;
391
392     assert (datalen >= sizeof(int *));
393     onOff = ((int *)data)[0];
394
395     if (onOff == 0 && sState != RADIO_STATE_OFF) {
396         err = at_send_command("AT+CFUN=0", &p_response);
397        if (err < 0 || p_response->success == 0) goto error;
398         setRadioState(RADIO_STATE_OFF);
399     } else if (onOff > 0 && sState == RADIO_STATE_OFF) {
400         err = at_send_command("AT+CFUN=1", &p_response);
401         if (err < 0|| p_response->success == 0) {
402             // Some stacks return an error when there is no SIM,
403             // but they really turn the RF portion on
404             // So, if we get an error, let's check to see if it
405             // turned on anyway
406
407             if (isRadioOn() != 1) {
408                 goto error;
409             }
410         }
411         setRadioState(RADIO_STATE_ON);
412     }
413
414     at_response_free(p_response);
415     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
416     return;
417 error:
418     at_response_free(p_response);
419     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
420 }
421
422 static void requestShutdown(RIL_Token t)
423 {
424     int onOff;
425
426     int err;
427     ATResponse *p_response = NULL;
428
429     if (sState != RADIO_STATE_OFF) {
430         err = at_send_command("AT+CFUN=0", &p_response);
431         setRadioState(RADIO_STATE_UNAVAILABLE);
432     }
433
434     at_response_free(p_response);
435     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
436     return;
437 }
438
439 static void requestOrSendDataCallList(RIL_Token *t);
440
441 static void onDataCallListChanged(void *param __unused)
442 {
443     requestOrSendDataCallList(NULL);
444 }
445
446 static void requestDataCallList(void *data __unused, size_t datalen __unused, RIL_Token t)
447 {
448     requestOrSendDataCallList(&t);
449 }
450
451 static void requestOrSendDataCallList(RIL_Token *t)
452 {
453     ATResponse *p_response;
454     ATLine *p_cur;
455     int err;
456     int n = 0;
457     char *out;
458
459     err = at_send_command_multiline ("AT+CGACT?", "+CGACT:", &p_response);
460     if (err != 0 || p_response->success == 0) {
461         if (t != NULL)
462             RIL_onRequestComplete(*t, RIL_E_GENERIC_FAILURE, NULL, 0);
463         else
464             RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
465                                       NULL, 0);
466         return;
467     }
468
469     for (p_cur = p_response->p_intermediates; p_cur != NULL;
470          p_cur = p_cur->p_next)
471         n++;
472
473     RIL_Data_Call_Response_v11 *responses =
474         alloca(n * sizeof(RIL_Data_Call_Response_v11));
475
476     int i;
477     for (i = 0; i < n; i++) {
478         responses[i].status = -1;
479         responses[i].suggestedRetryTime = -1;
480         responses[i].cid = -1;
481         responses[i].active = -1;
482         responses[i].type = "";
483         responses[i].ifname = "";
484         responses[i].addresses = "";
485         responses[i].dnses = "";
486         responses[i].gateways = "";
487         responses[i].pcscf = "";
488         responses[i].mtu = 0;
489     }
490
491     RIL_Data_Call_Response_v11 *response = responses;
492     for (p_cur = p_response->p_intermediates; p_cur != NULL;
493          p_cur = p_cur->p_next) {
494         char *line = p_cur->line;
495
496         err = at_tok_start(&line);
497         if (err < 0)
498             goto error;
499
500         err = at_tok_nextint(&line, &response->cid);
501         if (err < 0)
502             goto error;
503
504         err = at_tok_nextint(&line, &response->active);
505         if (err < 0)
506             goto error;
507
508         response++;
509     }
510
511     at_response_free(p_response);
512
513     err = at_send_command_multiline ("AT+CGDCONT?", "+CGDCONT:", &p_response);
514     if (err != 0 || p_response->success == 0) {
515         if (t != NULL)
516             RIL_onRequestComplete(*t, RIL_E_GENERIC_FAILURE, NULL, 0);
517         else
518             RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
519                                       NULL, 0);
520         return;
521     }
522
523     for (p_cur = p_response->p_intermediates; p_cur != NULL;
524          p_cur = p_cur->p_next) {
525         char *line = p_cur->line;
526         int cid;
527
528         err = at_tok_start(&line);
529         if (err < 0)
530             goto error;
531
532         err = at_tok_nextint(&line, &cid);
533         if (err < 0)
534             goto error;
535
536         for (i = 0; i < n; i++) {
537             if (responses[i].cid == cid)
538                 break;
539         }
540
541         if (i >= n) {
542             /* details for a context we didn't hear about in the last request */
543             continue;
544         }
545
546         // Assume no error
547         responses[i].status = 0;
548
549         // type
550         err = at_tok_nextstr(&line, &out);
551         if (err < 0)
552             goto error;
553
554         int type_size = strlen(out) + 1;
555         responses[i].type = alloca(type_size);
556         strlcpy(responses[i].type, out, type_size);
557
558         // APN ignored for v5
559         err = at_tok_nextstr(&line, &out);
560         if (err < 0)
561             goto error;
562
563         int ifname_size = strlen(PPP_TTY_PATH) + 1;
564         responses[i].ifname = alloca(ifname_size);
565         strlcpy(responses[i].ifname, PPP_TTY_PATH, ifname_size);
566
567         err = at_tok_nextstr(&line, &out);
568         if (err < 0)
569             goto error;
570
571         int addresses_size = strlen(out) + 1;
572         responses[i].addresses = alloca(addresses_size);
573         strlcpy(responses[i].addresses, out, addresses_size);
574
575         if (isInEmulator()) {
576             /* We are in the emulator - the dns servers are listed
577                 * by the following system properties, setup in
578                 * /system/etc/init.goldfish.sh:
579                 *  - net.eth0.dns1
580                 *  - net.eth0.dns2
581                 *  - net.eth0.dns3
582                 *  - net.eth0.dns4
583                 */
584             const int   dnslist_sz = 128;
585             char*       dnslist = alloca(dnslist_sz);
586             const char* separator = "";
587             int         nn;
588
589             dnslist[0] = 0;
590             for (nn = 1; nn <= 4; nn++) {
591                 /* Probe net.eth0.dns<n> */
592                 char  propName[PROP_NAME_MAX];
593                 char  propValue[PROP_VALUE_MAX];
594
595                 snprintf(propName, sizeof propName, "net.eth0.dns%d", nn);
596
597                 /* Ignore if undefined */
598                 if (__system_property_get(propName, propValue) == 0) {
599                     continue;
600                 }
601
602                 /* Append the DNS IP address */
603                 strlcat(dnslist, separator, dnslist_sz);
604                 strlcat(dnslist, propValue, dnslist_sz);
605                 separator = " ";
606             }
607             responses[i].dnses = dnslist;
608
609             responses[i].gateways = "10.0.2.2 fe80::2";
610             responses[i].mtu = DEFAULT_MTU;
611         }
612         else {
613             /* I don't know where we are, so use the public Google DNS
614                 * servers by default and no gateway.
615                 */
616             responses[i].dnses = "8.8.8.8 8.8.4.4";
617             responses[i].gateways = "";
618         }
619     }
620
621     at_response_free(p_response);
622
623     if (t != NULL)
624         RIL_onRequestComplete(*t, RIL_E_SUCCESS, responses,
625                               n * sizeof(RIL_Data_Call_Response_v11));
626     else
627         RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
628                                   responses,
629                                   n * sizeof(RIL_Data_Call_Response_v11));
630
631     return;
632
633 error:
634     if (t != NULL)
635         RIL_onRequestComplete(*t, RIL_E_GENERIC_FAILURE, NULL, 0);
636     else
637         RIL_onUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
638                                   NULL, 0);
639
640     at_response_free(p_response);
641 }
642
643 static void requestQueryNetworkSelectionMode(
644                 void *data __unused, size_t datalen __unused, RIL_Token t)
645 {
646     int err;
647     ATResponse *p_response = NULL;
648     int response = 0;
649     char *line;
650
651     err = at_send_command_singleline("AT+COPS?", "+COPS:", &p_response);
652
653     if (err < 0 || p_response->success == 0) {
654         goto error;
655     }
656
657     line = p_response->p_intermediates->line;
658
659     err = at_tok_start(&line);
660
661     if (err < 0) {
662         goto error;
663     }
664
665     err = at_tok_nextint(&line, &response);
666
667     if (err < 0) {
668         goto error;
669     }
670
671     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(int));
672     at_response_free(p_response);
673     return;
674 error:
675     at_response_free(p_response);
676     RLOGE("requestQueryNetworkSelectionMode must never return error when radio is on");
677     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
678 }
679
680 static void sendCallStateChanged(void *param __unused)
681 {
682     RIL_onUnsolicitedResponse (
683         RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
684         NULL, 0);
685 }
686
687 static void requestGetCurrentCalls(void *data __unused, size_t datalen __unused, RIL_Token t)
688 {
689     int err;
690     ATResponse *p_response;
691     ATLine *p_cur;
692     int countCalls;
693     int countValidCalls;
694     RIL_Call *p_calls;
695     RIL_Call **pp_calls;
696     int i;
697     int needRepoll = 0;
698
699 #ifdef WORKAROUND_ERRONEOUS_ANSWER
700     int prevIncomingOrWaitingLine;
701
702     prevIncomingOrWaitingLine = s_incomingOrWaitingLine;
703     s_incomingOrWaitingLine = -1;
704 #endif /*WORKAROUND_ERRONEOUS_ANSWER*/
705
706     err = at_send_command_multiline ("AT+CLCC", "+CLCC:", &p_response);
707
708     if (err != 0 || p_response->success == 0) {
709         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
710         return;
711     }
712
713     /* count the calls */
714     for (countCalls = 0, p_cur = p_response->p_intermediates
715             ; p_cur != NULL
716             ; p_cur = p_cur->p_next
717     ) {
718         countCalls++;
719     }
720
721     /* yes, there's an array of pointers and then an array of structures */
722
723     pp_calls = (RIL_Call **)alloca(countCalls * sizeof(RIL_Call *));
724     p_calls = (RIL_Call *)alloca(countCalls * sizeof(RIL_Call));
725     memset (p_calls, 0, countCalls * sizeof(RIL_Call));
726
727     /* init the pointer array */
728     for(i = 0; i < countCalls ; i++) {
729         pp_calls[i] = &(p_calls[i]);
730     }
731
732     for (countValidCalls = 0, p_cur = p_response->p_intermediates
733             ; p_cur != NULL
734             ; p_cur = p_cur->p_next
735     ) {
736         err = callFromCLCCLine(p_cur->line, p_calls + countValidCalls);
737
738         if (err != 0) {
739             continue;
740         }
741
742 #ifdef WORKAROUND_ERRONEOUS_ANSWER
743         if (p_calls[countValidCalls].state == RIL_CALL_INCOMING
744             || p_calls[countValidCalls].state == RIL_CALL_WAITING
745         ) {
746             s_incomingOrWaitingLine = p_calls[countValidCalls].index;
747         }
748 #endif /*WORKAROUND_ERRONEOUS_ANSWER*/
749
750         if (p_calls[countValidCalls].state != RIL_CALL_ACTIVE
751             && p_calls[countValidCalls].state != RIL_CALL_HOLDING
752         ) {
753             needRepoll = 1;
754         }
755
756         countValidCalls++;
757     }
758
759 #ifdef WORKAROUND_ERRONEOUS_ANSWER
760     // Basically:
761     // A call was incoming or waiting
762     // Now it's marked as active
763     // But we never answered it
764     //
765     // This is probably a bug, and the call will probably
766     // disappear from the call list in the next poll
767     if (prevIncomingOrWaitingLine >= 0
768             && s_incomingOrWaitingLine < 0
769             && s_expectAnswer == 0
770     ) {
771         for (i = 0; i < countValidCalls ; i++) {
772
773             if (p_calls[i].index == prevIncomingOrWaitingLine
774                     && p_calls[i].state == RIL_CALL_ACTIVE
775                     && s_repollCallsCount < REPOLL_CALLS_COUNT_MAX
776             ) {
777                 RLOGI(
778                     "Hit WORKAROUND_ERRONOUS_ANSWER case."
779                     " Repoll count: %d\n", s_repollCallsCount);
780                 s_repollCallsCount++;
781                 goto error;
782             }
783         }
784     }
785
786     s_expectAnswer = 0;
787     s_repollCallsCount = 0;
788 #endif /*WORKAROUND_ERRONEOUS_ANSWER*/
789
790     RIL_onRequestComplete(t, RIL_E_SUCCESS, pp_calls,
791             countValidCalls * sizeof (RIL_Call *));
792
793     at_response_free(p_response);
794
795 #ifdef POLL_CALL_STATE
796     if (countValidCalls) {  // We don't seem to get a "NO CARRIER" message from
797                             // smd, so we're forced to poll until the call ends.
798 #else
799     if (needRepoll) {
800 #endif
801         RIL_requestTimedCallback (sendCallStateChanged, NULL, &TIMEVAL_CALLSTATEPOLL);
802     }
803
804     return;
805 error:
806     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
807     at_response_free(p_response);
808 }
809
810 static void requestDial(void *data, size_t datalen __unused, RIL_Token t)
811 {
812     RIL_Dial *p_dial;
813     char *cmd;
814     const char *clir;
815     int ret;
816
817     p_dial = (RIL_Dial *)data;
818
819     switch (p_dial->clir) {
820         case 1: clir = "I"; break;  /*invocation*/
821         case 2: clir = "i"; break;  /*suppression*/
822         default:
823         case 0: clir = ""; break;   /*subscription default*/
824     }
825
826     asprintf(&cmd, "ATD%s%s;", p_dial->address, clir);
827
828     ret = at_send_command(cmd, NULL);
829
830     free(cmd);
831
832     /* success or failure is ignored by the upper layer here.
833        it will call GET_CURRENT_CALLS and determine success that way */
834     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
835 }
836
837 static void requestWriteSmsToSim(void *data, size_t datalen __unused, RIL_Token t)
838 {
839     RIL_SMS_WriteArgs *p_args;
840     char *cmd;
841     int length;
842     int err;
843     ATResponse *p_response = NULL;
844
845     p_args = (RIL_SMS_WriteArgs *)data;
846
847     length = strlen(p_args->pdu)/2;
848     asprintf(&cmd, "AT+CMGW=%d,%d", length, p_args->status);
849
850     err = at_send_command_sms(cmd, p_args->pdu, "+CMGW:", &p_response);
851
852     if (err != 0 || p_response->success == 0) goto error;
853
854     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
855     at_response_free(p_response);
856
857     return;
858 error:
859     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
860     at_response_free(p_response);
861 }
862
863 static void requestHangup(void *data, size_t datalen __unused, RIL_Token t)
864 {
865     int *p_line;
866
867     int ret;
868     char *cmd;
869
870     p_line = (int *)data;
871
872     // 3GPP 22.030 6.5.5
873     // "Releases a specific active call X"
874     asprintf(&cmd, "AT+CHLD=1%d", p_line[0]);
875
876     ret = at_send_command(cmd, NULL);
877
878     free(cmd);
879
880     /* success or failure is ignored by the upper layer here.
881        it will call GET_CURRENT_CALLS and determine success that way */
882     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
883 }
884
885 static void requestSignalStrength(void *data __unused, size_t datalen __unused, RIL_Token t)
886 {
887     ATResponse *p_response = NULL;
888     int err;
889     char *line;
890     int count =0;
891     int numofElements=sizeof(RIL_SignalStrength_v6)/sizeof(int);
892     int response[numofElements];
893
894     err = at_send_command_singleline("AT+CSQ", "+CSQ:", &p_response);
895
896     if (err < 0 || p_response->success == 0) {
897         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
898         goto error;
899     }
900
901     line = p_response->p_intermediates->line;
902
903     err = at_tok_start(&line);
904     if (err < 0) goto error;
905
906     for (count =0; count < numofElements; count ++) {
907         err = at_tok_nextint(&line, &(response[count]));
908         if (err < 0) goto error;
909     }
910
911     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
912
913     at_response_free(p_response);
914     return;
915
916 error:
917     RLOGE("requestSignalStrength must never return an error when radio is on");
918     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
919     at_response_free(p_response);
920 }
921
922 /**
923  * networkModePossible. Decides whether the network mode is appropriate for the
924  * specified modem
925  */
926 static int networkModePossible(ModemInfo *mdm, int nm)
927 {
928     if ((net2modem[nm] & mdm->supportedTechs) == net2modem[nm]) {
929        return 1;
930     }
931     return 0;
932 }
933 static void requestSetPreferredNetworkType( int request __unused, void *data,
934                                             size_t datalen __unused, RIL_Token t )
935 {
936     ATResponse *p_response = NULL;
937     char *cmd = NULL;
938     int value = *(int *)data;
939     int current, old;
940     int err;
941     int32_t preferred = net2pmask[value];
942
943     RLOGD("requestSetPreferredNetworkType: current: %x. New: %x", PREFERRED_NETWORK(sMdmInfo), preferred);
944     if (!networkModePossible(sMdmInfo, value)) {
945         RIL_onRequestComplete(t, RIL_E_MODE_NOT_SUPPORTED, NULL, 0);
946         return;
947     }
948     if (query_ctec(sMdmInfo, &current, NULL) < 0) {
949         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
950         return;
951     }
952     old = PREFERRED_NETWORK(sMdmInfo);
953     RLOGD("old != preferred: %d", old != preferred);
954     if (old != preferred) {
955         asprintf(&cmd, "AT+CTEC=%d,\"%x\"", current, preferred);
956         RLOGD("Sending command: <%s>", cmd);
957         err = at_send_command_singleline(cmd, "+CTEC:", &p_response);
958         free(cmd);
959         if (err || !p_response->success) {
960             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
961             return;
962         }
963         PREFERRED_NETWORK(sMdmInfo) = value;
964         if (!strstr( p_response->p_intermediates->line, "DONE") ) {
965             int current;
966             int res = parse_technology_response(p_response->p_intermediates->line, &current, NULL);
967             switch (res) {
968                 case -1: // Error or unable to parse
969                     break;
970                 case 1: // Only able to parse current
971                 case 0: // Both current and preferred were parsed
972                     setRadioTechnology(sMdmInfo, current);
973                     break;
974             }
975         }
976     }
977     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
978 }
979
980 static void requestGetPreferredNetworkType(int request __unused, void *data __unused,
981                                    size_t datalen __unused, RIL_Token t)
982 {
983     int preferred;
984     unsigned i;
985
986     switch ( query_ctec(sMdmInfo, NULL, &preferred) ) {
987         case -1: // Error or unable to parse
988         case 1: // Only able to parse current
989             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
990             break;
991         case 0: // Both current and preferred were parsed
992             for ( i = 0 ; i < sizeof(net2pmask) / sizeof(int32_t) ; i++ ) {
993                 if (preferred == net2pmask[i]) {
994                     RIL_onRequestComplete(t, RIL_E_SUCCESS, &i, sizeof(int));
995                     return;
996                 }
997             }
998             RLOGE("Unknown preferred mode received from modem: %d", preferred);
999             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1000             break;
1001     }
1002
1003 }
1004
1005 static void requestCdmaPrlVersion(int request __unused, void *data __unused,
1006                                    size_t datalen __unused, RIL_Token t)
1007 {
1008     int err;
1009     char * responseStr;
1010     ATResponse *p_response = NULL;
1011     const char *cmd;
1012     char *line;
1013
1014     err = at_send_command_singleline("AT+WPRL?", "+WPRL:", &p_response);
1015     if (err < 0 || !p_response->success) goto error;
1016     line = p_response->p_intermediates->line;
1017     err = at_tok_start(&line);
1018     if (err < 0) goto error;
1019     err = at_tok_nextstr(&line, &responseStr);
1020     if (err < 0 || !responseStr) goto error;
1021     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, strlen(responseStr));
1022     at_response_free(p_response);
1023     return;
1024 error:
1025     at_response_free(p_response);
1026     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1027 }
1028
1029 static void requestCdmaBaseBandVersion(int request __unused, void *data __unused,
1030                                    size_t datalen __unused, RIL_Token t)
1031 {
1032     int err;
1033     char * responseStr;
1034     ATResponse *p_response = NULL;
1035     const char *cmd;
1036     const char *prefix;
1037     char *line, *p;
1038     int commas;
1039     int skip;
1040     int count = 4;
1041
1042     // Fixed values. TODO: query modem
1043     responseStr = strdup("1.0.0.0");
1044     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, sizeof(responseStr));
1045     free(responseStr);
1046 }
1047
1048 static void requestCdmaDeviceIdentity(int request __unused, void *data __unused,
1049                                         size_t datalen __unused, RIL_Token t)
1050 {
1051     int err;
1052     int response[4];
1053     char * responseStr[4];
1054     ATResponse *p_response = NULL;
1055     const char *cmd;
1056     const char *prefix;
1057     char *line, *p;
1058     int commas;
1059     int skip;
1060     int count = 4;
1061
1062     // Fixed values. TODO: Query modem
1063     responseStr[0] = "----";
1064     responseStr[1] = "----";
1065     responseStr[2] = "77777777";
1066
1067     err = at_send_command_numeric("AT+CGSN", &p_response);
1068     if (err < 0 || p_response->success == 0) {
1069         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1070         return;
1071     } else {
1072         responseStr[3] = p_response->p_intermediates->line;
1073     }
1074
1075     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, count*sizeof(char*));
1076     at_response_free(p_response);
1077
1078     return;
1079 error:
1080     RLOGE("requestCdmaDeviceIdentity must never return an error when radio is on");
1081     at_response_free(p_response);
1082     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1083 }
1084
1085 static void requestCdmaGetSubscriptionSource(int request __unused, void *data,
1086                                         size_t datalen __unused, RIL_Token t)
1087 {
1088     int err;
1089     int *ss = (int *)data;
1090     ATResponse *p_response = NULL;
1091     char *cmd = NULL;
1092     char *line = NULL;
1093     int response;
1094
1095     asprintf(&cmd, "AT+CCSS?");
1096     if (!cmd) goto error;
1097
1098     err = at_send_command_singleline(cmd, "+CCSS:", &p_response);
1099     if (err < 0 || !p_response->success)
1100         goto error;
1101
1102     line = p_response->p_intermediates->line;
1103     err = at_tok_start(&line);
1104     if (err < 0) goto error;
1105
1106     err = at_tok_nextint(&line, &response);
1107     free(cmd);
1108     cmd = NULL;
1109
1110     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
1111
1112     return;
1113 error:
1114     free(cmd);
1115     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1116 }
1117
1118 static void requestCdmaSetSubscriptionSource(int request __unused, void *data,
1119                                         size_t datalen, RIL_Token t)
1120 {
1121     int err;
1122     int *ss = (int *)data;
1123     ATResponse *p_response = NULL;
1124     char *cmd = NULL;
1125
1126     if (!ss || !datalen) {
1127         RLOGE("RIL_REQUEST_CDMA_SET_SUBSCRIPTION without data!");
1128         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1129         return;
1130     }
1131     asprintf(&cmd, "AT+CCSS=%d", ss[0]);
1132     if (!cmd) goto error;
1133
1134     err = at_send_command(cmd, &p_response);
1135     if (err < 0 || !p_response->success)
1136         goto error;
1137     free(cmd);
1138     cmd = NULL;
1139
1140     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1141
1142     RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED, ss, sizeof(ss[0]));
1143
1144     return;
1145 error:
1146     free(cmd);
1147     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1148 }
1149
1150 static void requestCdmaSubscription(int request __unused, void *data __unused,
1151                                         size_t datalen __unused, RIL_Token t)
1152 {
1153     int err;
1154     int response[5];
1155     char * responseStr[5];
1156     ATResponse *p_response = NULL;
1157     const char *cmd;
1158     const char *prefix;
1159     char *line, *p;
1160     int commas;
1161     int skip;
1162     int count = 5;
1163
1164     // Fixed values. TODO: Query modem
1165     responseStr[0] = "8587777777"; // MDN
1166     responseStr[1] = "1"; // SID
1167     responseStr[2] = "1"; // NID
1168     responseStr[3] = "8587777777"; // MIN
1169     responseStr[4] = "1"; // PRL Version
1170     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, count*sizeof(char*));
1171
1172     return;
1173 error:
1174     RLOGE("requestRegistrationState must never return an error when radio is on");
1175     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1176 }
1177
1178 static void requestCdmaGetRoamingPreference(int request __unused, void *data __unused,
1179                                                  size_t datalen __unused, RIL_Token t)
1180 {
1181     int roaming_pref = -1;
1182     ATResponse *p_response = NULL;
1183     char *line;
1184     int res;
1185
1186     res = at_send_command_singleline("AT+WRMP?", "+WRMP:", &p_response);
1187     if (res < 0 || !p_response->success) {
1188         goto error;
1189     }
1190     line = p_response->p_intermediates->line;
1191
1192     res = at_tok_start(&line);
1193     if (res < 0) goto error;
1194
1195     res = at_tok_nextint(&line, &roaming_pref);
1196     if (res < 0) goto error;
1197
1198      RIL_onRequestComplete(t, RIL_E_SUCCESS, &roaming_pref, sizeof(roaming_pref));
1199     return;
1200 error:
1201     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1202 }
1203
1204 static void requestCdmaSetRoamingPreference(int request __unused, void *data,
1205                                                  size_t datalen __unused, RIL_Token t)
1206 {
1207     int *pref = (int *)data;
1208     ATResponse *p_response = NULL;
1209     char *line;
1210     int res;
1211     char *cmd = NULL;
1212
1213     asprintf(&cmd, "AT+WRMP=%d", *pref);
1214     if (cmd == NULL) goto error;
1215
1216     res = at_send_command(cmd, &p_response);
1217     if (res < 0 || !p_response->success)
1218         goto error;
1219
1220     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1221     free(cmd);
1222     return;
1223 error:
1224     free(cmd);
1225     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1226 }
1227
1228 static int parseRegistrationState(char *str, int *type, int *items, int **response)
1229 {
1230     int err;
1231     char *line = str, *p;
1232     int *resp = NULL;
1233     int skip;
1234     int count = 3;
1235     int commas;
1236
1237     RLOGD("parseRegistrationState. Parsing: %s",str);
1238     err = at_tok_start(&line);
1239     if (err < 0) goto error;
1240
1241     /* Ok you have to be careful here
1242      * The solicited version of the CREG response is
1243      * +CREG: n, stat, [lac, cid]
1244      * and the unsolicited version is
1245      * +CREG: stat, [lac, cid]
1246      * The <n> parameter is basically "is unsolicited creg on?"
1247      * which it should always be
1248      *
1249      * Now we should normally get the solicited version here,
1250      * but the unsolicited version could have snuck in
1251      * so we have to handle both
1252      *
1253      * Also since the LAC and CID are only reported when registered,
1254      * we can have 1, 2, 3, or 4 arguments here
1255      *
1256      * finally, a +CGREG: answer may have a fifth value that corresponds
1257      * to the network type, as in;
1258      *
1259      *   +CGREG: n, stat [,lac, cid [,networkType]]
1260      */
1261
1262     /* count number of commas */
1263     commas = 0;
1264     for (p = line ; *p != '\0' ;p++) {
1265         if (*p == ',') commas++;
1266     }
1267
1268     resp = (int *)calloc(commas + 1, sizeof(int));
1269     if (!resp) goto error;
1270     switch (commas) {
1271         case 0: /* +CREG: <stat> */
1272             err = at_tok_nextint(&line, &resp[0]);
1273             if (err < 0) goto error;
1274             resp[1] = -1;
1275             resp[2] = -1;
1276         break;
1277
1278         case 1: /* +CREG: <n>, <stat> */
1279             err = at_tok_nextint(&line, &skip);
1280             if (err < 0) goto error;
1281             err = at_tok_nextint(&line, &resp[0]);
1282             if (err < 0) goto error;
1283             resp[1] = -1;
1284             resp[2] = -1;
1285             if (err < 0) goto error;
1286         break;
1287
1288         case 2: /* +CREG: <stat>, <lac>, <cid> */
1289             err = at_tok_nextint(&line, &resp[0]);
1290             if (err < 0) goto error;
1291             err = at_tok_nexthexint(&line, &resp[1]);
1292             if (err < 0) goto error;
1293             err = at_tok_nexthexint(&line, &resp[2]);
1294             if (err < 0) goto error;
1295         break;
1296         case 3: /* +CREG: <n>, <stat>, <lac>, <cid> */
1297             err = at_tok_nextint(&line, &skip);
1298             if (err < 0) goto error;
1299             err = at_tok_nextint(&line, &resp[0]);
1300             if (err < 0) goto error;
1301             err = at_tok_nexthexint(&line, &resp[1]);
1302             if (err < 0) goto error;
1303             err = at_tok_nexthexint(&line, &resp[2]);
1304             if (err < 0) goto error;
1305         break;
1306         /* special case for CGREG, there is a fourth parameter
1307          * that is the network type (unknown/gprs/edge/umts)
1308          */
1309         case 4: /* +CGREG: <n>, <stat>, <lac>, <cid>, <networkType> */
1310             err = at_tok_nextint(&line, &skip);
1311             if (err < 0) goto error;
1312             err = at_tok_nextint(&line, &resp[0]);
1313             if (err < 0) goto error;
1314             err = at_tok_nexthexint(&line, &resp[1]);
1315             if (err < 0) goto error;
1316             err = at_tok_nexthexint(&line, &resp[2]);
1317             if (err < 0) goto error;
1318             err = at_tok_nexthexint(&line, &resp[3]);
1319             if (err < 0) goto error;
1320             count = 4;
1321         break;
1322         default:
1323             goto error;
1324     }
1325     s_lac = resp[1];
1326     s_cid = resp[2];
1327     if (response)
1328         *response = resp;
1329     if (items)
1330         *items = commas + 1;
1331     if (type)
1332         *type = techFromModemType(TECH(sMdmInfo));
1333     return 0;
1334 error:
1335     free(resp);
1336     return -1;
1337 }
1338
1339 #define REG_STATE_LEN 15
1340 #define REG_DATA_STATE_LEN 6
1341 static void requestRegistrationState(int request, void *data __unused,
1342                                         size_t datalen __unused, RIL_Token t)
1343 {
1344     int err;
1345     int *registration;
1346     char **responseStr = NULL;
1347     ATResponse *p_response = NULL;
1348     const char *cmd;
1349     const char *prefix;
1350     char *line;
1351     int i = 0, j, numElements = 0;
1352     int count = 3;
1353     int type, startfrom;
1354
1355     RLOGD("requestRegistrationState");
1356     if (request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
1357         cmd = "AT+CREG?";
1358         prefix = "+CREG:";
1359         numElements = REG_STATE_LEN;
1360     } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1361         cmd = "AT+CGREG?";
1362         prefix = "+CGREG:";
1363         numElements = REG_DATA_STATE_LEN;
1364     } else {
1365         assert(0);
1366         goto error;
1367     }
1368
1369     err = at_send_command_singleline(cmd, prefix, &p_response);
1370
1371     if (err != 0) goto error;
1372
1373     line = p_response->p_intermediates->line;
1374
1375     if (parseRegistrationState(line, &type, &count, &registration)) goto error;
1376
1377     responseStr = malloc(numElements * sizeof(char *));
1378     if (!responseStr) goto error;
1379     memset(responseStr, 0, numElements * sizeof(char *));
1380     /**
1381      * The first '4' bytes for both registration states remain the same.
1382      * But if the request is 'DATA_REGISTRATION_STATE',
1383      * the 5th and 6th byte(s) are optional.
1384      */
1385     if (is3gpp2(type) == 1) {
1386         RLOGD("registration state type: 3GPP2");
1387         // TODO: Query modem
1388         startfrom = 3;
1389         if(request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
1390             asprintf(&responseStr[3], "8");     // EvDo revA
1391             asprintf(&responseStr[4], "1");     // BSID
1392             asprintf(&responseStr[5], "123");   // Latitude
1393             asprintf(&responseStr[6], "222");   // Longitude
1394             asprintf(&responseStr[7], "0");     // CSS Indicator
1395             asprintf(&responseStr[8], "4");     // SID
1396             asprintf(&responseStr[9], "65535"); // NID
1397             asprintf(&responseStr[10], "0");    // Roaming indicator
1398             asprintf(&responseStr[11], "1");    // System is in PRL
1399             asprintf(&responseStr[12], "0");    // Default Roaming indicator
1400             asprintf(&responseStr[13], "0");    // Reason for denial
1401             asprintf(&responseStr[14], "0");    // Primary Scrambling Code of Current cell
1402       } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1403             asprintf(&responseStr[3], "8");   // Available data radio technology
1404       }
1405     } else { // type == RADIO_TECH_3GPP
1406         RLOGD("registration state type: 3GPP");
1407         startfrom = 0;
1408         asprintf(&responseStr[1], "%x", registration[1]);
1409         asprintf(&responseStr[2], "%x", registration[2]);
1410         if (count > 3)
1411             asprintf(&responseStr[3], "%d", registration[3]);
1412     }
1413     asprintf(&responseStr[0], "%d", registration[0]);
1414
1415     /**
1416      * Optional bytes for DATA_REGISTRATION_STATE request
1417      * 4th byte : Registration denial code
1418      * 5th byte : The max. number of simultaneous Data Calls
1419      */
1420     if(request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1421         // asprintf(&responseStr[4], "3");
1422         // asprintf(&responseStr[5], "1");
1423     }
1424
1425     for (j = startfrom; j < numElements; j++) {
1426         if (!responseStr[i]) goto error;
1427     }
1428     free(registration);
1429     registration = NULL;
1430
1431     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, numElements*sizeof(responseStr));
1432     for (j = 0; j < numElements; j++ ) {
1433         free(responseStr[j]);
1434         responseStr[j] = NULL;
1435     }
1436     free(responseStr);
1437     responseStr = NULL;
1438     at_response_free(p_response);
1439
1440     return;
1441 error:
1442     if (responseStr) {
1443         for (j = 0; j < numElements; j++) {
1444             free(responseStr[j]);
1445             responseStr[j] = NULL;
1446         }
1447         free(responseStr);
1448         responseStr = NULL;
1449     }
1450     RLOGE("requestRegistrationState must never return an error when radio is on");
1451     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1452     at_response_free(p_response);
1453 }
1454
1455 static void requestOperator(void *data __unused, size_t datalen __unused, RIL_Token t)
1456 {
1457     int err;
1458     int i;
1459     int skip;
1460     ATLine *p_cur;
1461     char *response[3];
1462
1463     memset(response, 0, sizeof(response));
1464
1465     ATResponse *p_response = NULL;
1466
1467     err = at_send_command_multiline(
1468         "AT+COPS=3,0;+COPS?;+COPS=3,1;+COPS?;+COPS=3,2;+COPS?",
1469         "+COPS:", &p_response);
1470
1471     /* we expect 3 lines here:
1472      * +COPS: 0,0,"T - Mobile"
1473      * +COPS: 0,1,"TMO"
1474      * +COPS: 0,2,"310170"
1475      */
1476
1477     if (err != 0) goto error;
1478
1479     for (i = 0, p_cur = p_response->p_intermediates
1480             ; p_cur != NULL
1481             ; p_cur = p_cur->p_next, i++
1482     ) {
1483         char *line = p_cur->line;
1484
1485         err = at_tok_start(&line);
1486         if (err < 0) goto error;
1487
1488         err = at_tok_nextint(&line, &skip);
1489         if (err < 0) goto error;
1490
1491         // If we're unregistered, we may just get
1492         // a "+COPS: 0" response
1493         if (!at_tok_hasmore(&line)) {
1494             response[i] = NULL;
1495             continue;
1496         }
1497
1498         err = at_tok_nextint(&line, &skip);
1499         if (err < 0) goto error;
1500
1501         // a "+COPS: 0, n" response is also possible
1502         if (!at_tok_hasmore(&line)) {
1503             response[i] = NULL;
1504             continue;
1505         }
1506
1507         err = at_tok_nextstr(&line, &(response[i]));
1508         if (err < 0) goto error;
1509         // Simple assumption that mcc and mnc are 3 digits each
1510         if (strlen(response[i]) == 6) {
1511             if (sscanf(response[i], "%3d%3d", &s_mcc, &s_mnc) != 2) {
1512                 RLOGE("requestOperator expected mccmnc to be 6 decimal digits");
1513             }
1514         }
1515     }
1516
1517     if (i != 3) {
1518         /* expect 3 lines exactly */
1519         goto error;
1520     }
1521
1522     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
1523     at_response_free(p_response);
1524
1525     return;
1526 error:
1527     RLOGE("requestOperator must not return error when radio is on");
1528     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1529     at_response_free(p_response);
1530 }
1531
1532 static void requestCdmaSendSMS(void *data, size_t datalen, RIL_Token t)
1533 {
1534     int err = 1; // Set to go to error:
1535     RIL_SMS_Response response;
1536     RIL_CDMA_SMS_Message* rcsm;
1537
1538     RLOGD("requestCdmaSendSMS datalen=%zu, sizeof(RIL_CDMA_SMS_Message)=%zu",
1539             datalen, sizeof(RIL_CDMA_SMS_Message));
1540
1541     // verify data content to test marshalling/unmarshalling:
1542     rcsm = (RIL_CDMA_SMS_Message*)data;
1543     RLOGD("TeleserviceID=%d, bIsServicePresent=%d, \
1544             uServicecategory=%d, sAddress.digit_mode=%d, \
1545             sAddress.Number_mode=%d, sAddress.number_type=%d, ",
1546             rcsm->uTeleserviceID,  rcsm->bIsServicePresent,
1547             rcsm->uServicecategory,rcsm->sAddress.digit_mode,
1548             rcsm->sAddress.number_mode,rcsm->sAddress.number_type);
1549
1550     if (err != 0) goto error;
1551
1552     // Cdma Send SMS implementation will go here:
1553     // But it is not implemented yet.
1554
1555     memset(&response, 0, sizeof(response));
1556     response.messageRef = 1;
1557     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
1558     return;
1559
1560 error:
1561     // Cdma Send SMS will always cause send retry error.
1562     response.messageRef = -1;
1563     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
1564 }
1565
1566 static void requestSendSMS(void *data, size_t datalen, RIL_Token t)
1567 {
1568     int err;
1569     const char *smsc;
1570     const char *pdu;
1571     int tpLayerLength;
1572     char *cmd1, *cmd2;
1573     RIL_SMS_Response response;
1574     ATResponse *p_response = NULL;
1575
1576     memset(&response, 0, sizeof(response));
1577     RLOGD("requestSendSMS datalen =%zu", datalen);
1578
1579     if (s_ims_gsm_fail != 0) goto error;
1580     if (s_ims_gsm_retry != 0) goto error2;
1581
1582     smsc = ((const char **)data)[0];
1583     pdu = ((const char **)data)[1];
1584
1585     tpLayerLength = strlen(pdu)/2;
1586
1587     // "NULL for default SMSC"
1588     if (smsc == NULL) {
1589         smsc= "00";
1590     }
1591
1592     asprintf(&cmd1, "AT+CMGS=%d", tpLayerLength);
1593     asprintf(&cmd2, "%s%s", smsc, pdu);
1594
1595     err = at_send_command_sms(cmd1, cmd2, "+CMGS:", &p_response);
1596
1597     free(cmd1);
1598     free(cmd2);
1599
1600     if (err != 0 || p_response->success == 0) goto error;
1601
1602     /* FIXME fill in messageRef and ackPDU */
1603     response.messageRef = 1;
1604     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
1605     at_response_free(p_response);
1606
1607     return;
1608 error:
1609     response.messageRef = -2;
1610     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, &response, sizeof(response));
1611     at_response_free(p_response);
1612     return;
1613 error2:
1614     // send retry error.
1615     response.messageRef = -1;
1616     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
1617     at_response_free(p_response);
1618     return;
1619     }
1620
1621 static void requestImsSendSMS(void *data, size_t datalen, RIL_Token t)
1622 {
1623     RIL_IMS_SMS_Message *p_args;
1624     RIL_SMS_Response response;
1625
1626     memset(&response, 0, sizeof(response));
1627
1628     RLOGD("requestImsSendSMS: datalen=%zu, "
1629         "registered=%d, service=%d, format=%d, ims_perm_fail=%d, "
1630         "ims_retry=%d, gsm_fail=%d, gsm_retry=%d",
1631         datalen, s_ims_registered, s_ims_services, s_ims_format,
1632         s_ims_cause_perm_failure, s_ims_cause_retry, s_ims_gsm_fail,
1633         s_ims_gsm_retry);
1634
1635     // figure out if this is gsm/cdma format
1636     // then route it to requestSendSMS vs requestCdmaSendSMS respectively
1637     p_args = (RIL_IMS_SMS_Message *)data;
1638
1639     if (0 != s_ims_cause_perm_failure ) goto error;
1640
1641     // want to fail over ims and this is first request over ims
1642     if (0 != s_ims_cause_retry && 0 == p_args->retry) goto error2;
1643
1644     if (RADIO_TECH_3GPP == p_args->tech) {
1645         return requestSendSMS(p_args->message.gsmMessage,
1646                 datalen - sizeof(RIL_RadioTechnologyFamily),
1647                 t);
1648     } else if (RADIO_TECH_3GPP2 == p_args->tech) {
1649         return requestCdmaSendSMS(p_args->message.cdmaMessage,
1650                 datalen - sizeof(RIL_RadioTechnologyFamily),
1651                 t);
1652     } else {
1653         RLOGE("requestImsSendSMS invalid format value =%d", p_args->tech);
1654     }
1655
1656 error:
1657     response.messageRef = -2;
1658     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, &response, sizeof(response));
1659     return;
1660
1661 error2:
1662     response.messageRef = -1;
1663     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
1664 }
1665
1666 static void requestSimOpenChannel(void *data, size_t datalen, RIL_Token t)
1667 {
1668     ATResponse *p_response = NULL;
1669     int32_t session_id;
1670     int err;
1671     char cmd[32];
1672     char dummy;
1673     char *line;
1674
1675     // Max length is 16 bytes according to 3GPP spec 27.007 section 8.45
1676     if (data == NULL || datalen == 0 || datalen > 16) {
1677         ALOGE("Invalid data passed to requestSimOpenChannel");
1678         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1679         return;
1680     }
1681
1682     snprintf(cmd, sizeof(cmd), "AT+CCHO=%s", data);
1683
1684     err = at_send_command_numeric(cmd, &p_response);
1685     if (err < 0 || p_response == NULL || p_response->success == 0) {
1686         ALOGE("Error %d opening logical channel: %d",
1687               err, p_response ? p_response->success : 0);
1688         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1689         at_response_free(p_response);
1690         return;
1691     }
1692
1693     // Ensure integer only by scanning for an extra char but expect one result
1694     line = p_response->p_intermediates->line;
1695     if (sscanf(line, "%" SCNd32 "%c", &session_id, &dummy) != 1) {
1696         ALOGE("Invalid AT response, expected integer, was '%s'", line);
1697         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1698         return;
1699     }
1700
1701     RIL_onRequestComplete(t, RIL_E_SUCCESS, &session_id, sizeof(&session_id));
1702     at_response_free(p_response);
1703 }
1704
1705 static void requestSimCloseChannel(void *data, size_t datalen, RIL_Token t)
1706 {
1707     ATResponse *p_response = NULL;
1708     int32_t session_id;
1709     int err;
1710     char cmd[32];
1711
1712     if (data == NULL || datalen != sizeof(session_id)) {
1713         ALOGE("Invalid data passed to requestSimCloseChannel");
1714         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1715         return;
1716     }
1717     session_id = ((int32_t *)data)[0];
1718     snprintf(cmd, sizeof(cmd), "AT+CCHC=%" PRId32, session_id);
1719     err = at_send_command_singleline(cmd, "+CCHC", &p_response);
1720
1721     if (err < 0 || p_response == NULL || p_response->success == 0) {
1722         ALOGE("Error %d closing logical channel %d: %d",
1723               err, session_id, p_response ? p_response->success : 0);
1724         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1725         at_response_free(p_response);
1726         return;
1727     }
1728
1729     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1730
1731     at_response_free(p_response);
1732 }
1733
1734 static void requestSimTransmitApduChannel(void *data,
1735                                           size_t datalen,
1736                                           RIL_Token t)
1737 {
1738     ATResponse *p_response = NULL;
1739     int err;
1740     char *cmd;
1741     char *line;
1742     size_t cmd_size;
1743     RIL_SIM_IO_Response sim_response;
1744     RIL_SIM_APDU *apdu = (RIL_SIM_APDU *)data;
1745
1746     if (apdu == NULL || datalen != sizeof(RIL_SIM_APDU)) {
1747         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1748         return;
1749     }
1750
1751     cmd_size = 10 + (apdu->data ? strlen(apdu->data) : 0);
1752     asprintf(&cmd, "AT+CGLA=%d,%zu,%02x%02x%02x%02x%02x%s",
1753              apdu->sessionid, cmd_size, apdu->cla, apdu->instruction,
1754              apdu->p1, apdu->p2, apdu->p3, apdu->data ? apdu->data : "");
1755
1756     err = at_send_command_singleline(cmd, "+CGLA", &p_response);
1757     free(cmd);
1758     if (err < 0 || p_response == NULL || p_response->success == 0) {
1759         ALOGE("Error %d transmitting APDU: %d",
1760               err, p_response ? p_response->success : 0);
1761         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1762         at_response_free(p_response);
1763         return;
1764     }
1765
1766     line = p_response->p_intermediates->line;
1767     err = parseSimResponseLine(line, &sim_response);
1768
1769     if (err == 0) {
1770         RIL_onRequestComplete(t, RIL_E_SUCCESS,
1771                               &sim_response, sizeof(sim_response));
1772     } else {
1773         ALOGE("Error %d parsing SIM response line: %s", err, line);
1774         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1775     }
1776     at_response_free(p_response);
1777 }
1778
1779 static void requestSetupDataCall(void *data, size_t datalen, RIL_Token t)
1780 {
1781     const char *apn;
1782     char *cmd;
1783     int err;
1784     ATResponse *p_response = NULL;
1785
1786     apn = ((const char **)data)[2];
1787
1788 #ifdef USE_TI_COMMANDS
1789     // Config for multislot class 10 (probably default anyway eh?)
1790     err = at_send_command("AT%CPRIM=\"GMM\",\"CONFIG MULTISLOT_CLASS=<10>\"",
1791                         NULL);
1792
1793     err = at_send_command("AT%DATA=2,\"UART\",1,,\"SER\",\"UART\",0", NULL);
1794 #endif /* USE_TI_COMMANDS */
1795
1796     int fd, qmistatus;
1797     size_t cur = 0;
1798     size_t len;
1799     ssize_t written, rlen;
1800     char status[32] = {0};
1801     int retry = 10;
1802     const char *pdp_type;
1803
1804     RLOGD("requesting data connection to APN '%s'", apn);
1805
1806     fd = open ("/dev/qmi", O_RDWR);
1807     if (fd >= 0) { /* the device doesn't exist on the emulator */
1808
1809         RLOGD("opened the qmi device\n");
1810         asprintf(&cmd, "up:%s", apn);
1811         len = strlen(cmd);
1812
1813         while (cur < len) {
1814             do {
1815                 written = write (fd, cmd + cur, len - cur);
1816             } while (written < 0 && errno == EINTR);
1817
1818             if (written < 0) {
1819                 RLOGE("### ERROR writing to /dev/qmi");
1820                 close(fd);
1821                 goto error;
1822             }
1823
1824             cur += written;
1825         }
1826
1827         // wait for interface to come online
1828
1829         do {
1830             sleep(1);
1831             do {
1832                 rlen = read(fd, status, 31);
1833             } while (rlen < 0 && errno == EINTR);
1834
1835             if (rlen < 0) {
1836                 RLOGE("### ERROR reading from /dev/qmi");
1837                 close(fd);
1838                 goto error;
1839             } else {
1840                 status[rlen] = '\0';
1841                 RLOGD("### status: %s", status);
1842             }
1843         } while (strncmp(status, "STATE=up", 8) && strcmp(status, "online") && --retry);
1844
1845         close(fd);
1846
1847         if (retry == 0) {
1848             RLOGE("### Failed to get data connection up\n");
1849             goto error;
1850         }
1851
1852         qmistatus = system("netcfg rmnet0 dhcp");
1853
1854         RLOGD("netcfg rmnet0 dhcp: status %d\n", qmistatus);
1855
1856         if (qmistatus < 0) goto error;
1857
1858     } else {
1859
1860         if (datalen > 6 * sizeof(char *)) {
1861             pdp_type = ((const char **)data)[6];
1862         } else {
1863             pdp_type = "IP";
1864         }
1865
1866         asprintf(&cmd, "AT+CGDCONT=1,\"%s\",\"%s\",,0,0", pdp_type, apn);
1867         //FIXME check for error here
1868         err = at_send_command(cmd, NULL);
1869         free(cmd);
1870
1871         // Set required QoS params to default
1872         err = at_send_command("AT+CGQREQ=1", NULL);
1873
1874         // Set minimum QoS params to default
1875         err = at_send_command("AT+CGQMIN=1", NULL);
1876
1877         // packet-domain event reporting
1878         err = at_send_command("AT+CGEREP=1,0", NULL);
1879
1880         // Hangup anything that's happening there now
1881         err = at_send_command("AT+CGACT=1,0", NULL);
1882
1883         // Start data on PDP context 1
1884         err = at_send_command("ATD*99***1#", &p_response);
1885
1886         if (err < 0 || p_response->success == 0) {
1887             goto error;
1888         }
1889     }
1890
1891     requestOrSendDataCallList(&t);
1892
1893     at_response_free(p_response);
1894
1895     return;
1896 error:
1897     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1898     at_response_free(p_response);
1899
1900 }
1901
1902 static void requestSMSAcknowledge(void *data, size_t datalen __unused, RIL_Token t)
1903 {
1904     int ackSuccess;
1905     int err;
1906
1907     ackSuccess = ((int *)data)[0];
1908
1909     if (ackSuccess == 1) {
1910         err = at_send_command("AT+CNMA=1", NULL);
1911     } else if (ackSuccess == 0)  {
1912         err = at_send_command("AT+CNMA=2", NULL);
1913     } else {
1914         RLOGE("unsupported arg to RIL_REQUEST_SMS_ACKNOWLEDGE\n");
1915         goto error;
1916     }
1917
1918     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1919 error:
1920     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1921
1922 }
1923
1924 static void  requestSIM_IO(void *data, size_t datalen __unused, RIL_Token t)
1925 {
1926     ATResponse *p_response = NULL;
1927     RIL_SIM_IO_Response sr;
1928     int err;
1929     char *cmd = NULL;
1930     RIL_SIM_IO_v6 *p_args;
1931     char *line;
1932
1933     memset(&sr, 0, sizeof(sr));
1934
1935     p_args = (RIL_SIM_IO_v6 *)data;
1936
1937     /* FIXME handle pin2 */
1938
1939     if (p_args->data == NULL) {
1940         asprintf(&cmd, "AT+CRSM=%d,%d,%d,%d,%d",
1941                     p_args->command, p_args->fileid,
1942                     p_args->p1, p_args->p2, p_args->p3);
1943     } else {
1944         asprintf(&cmd, "AT+CRSM=%d,%d,%d,%d,%d,%s",
1945                     p_args->command, p_args->fileid,
1946                     p_args->p1, p_args->p2, p_args->p3, p_args->data);
1947     }
1948
1949     err = at_send_command_singleline(cmd, "+CRSM:", &p_response);
1950
1951     if (err < 0 || p_response->success == 0) {
1952         goto error;
1953     }
1954
1955     line = p_response->p_intermediates->line;
1956
1957     err = parseSimResponseLine(line, &sr);
1958     if (err < 0) {
1959         goto error;
1960     }
1961
1962     RIL_onRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
1963     at_response_free(p_response);
1964     free(cmd);
1965
1966     return;
1967 error:
1968     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1969     at_response_free(p_response);
1970     free(cmd);
1971
1972 }
1973
1974 static void  requestEnterSimPin(void*  data, size_t  datalen, RIL_Token  t)
1975 {
1976     ATResponse   *p_response = NULL;
1977     int           err;
1978     char*         cmd = NULL;
1979     const char**  strings = (const char**)data;;
1980
1981     if ( datalen == sizeof(char*) ) {
1982         asprintf(&cmd, "AT+CPIN=%s", strings[0]);
1983     } else if ( datalen == 2*sizeof(char*) ) {
1984         asprintf(&cmd, "AT+CPIN=%s,%s", strings[0], strings[1]);
1985     } else
1986         goto error;
1987
1988     err = at_send_command_singleline(cmd, "+CPIN:", &p_response);
1989     free(cmd);
1990
1991     if (err < 0 || p_response->success == 0) {
1992 error:
1993         RIL_onRequestComplete(t, RIL_E_PASSWORD_INCORRECT, NULL, 0);
1994     } else {
1995         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1996     }
1997     at_response_free(p_response);
1998 }
1999
2000
2001 static void  requestSendUSSD(void *data, size_t datalen __unused, RIL_Token t)
2002 {
2003     const char *ussdRequest;
2004
2005     ussdRequest = (char *)(data);
2006
2007
2008     RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
2009
2010 // @@@ TODO
2011
2012 }
2013
2014 static void requestExitEmergencyMode(void *data __unused, size_t datalen __unused, RIL_Token t)
2015 {
2016     int err;
2017     ATResponse *p_response = NULL;
2018
2019     err = at_send_command("AT+WSOS=0", &p_response);
2020
2021     if (err < 0 || p_response->success == 0) {
2022         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2023         return;
2024     }
2025
2026     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2027 }
2028
2029 // TODO: Use all radio types
2030 static int techFromModemType(int mdmtype)
2031 {
2032     int ret = -1;
2033     switch (1 << mdmtype) {
2034         case MDM_CDMA:
2035             ret = RADIO_TECH_1xRTT;
2036             break;
2037         case MDM_EVDO:
2038             ret = RADIO_TECH_EVDO_A;
2039             break;
2040         case MDM_GSM:
2041             ret = RADIO_TECH_GPRS;
2042             break;
2043         case MDM_WCDMA:
2044             ret = RADIO_TECH_HSPA;
2045             break;
2046         case MDM_LTE:
2047             ret = RADIO_TECH_LTE;
2048             break;
2049     }
2050     return ret;
2051 }
2052
2053 static void requestGetCellInfoList(void *data __unused, size_t datalen __unused, RIL_Token t)
2054 {
2055     uint64_t curTime = ril_nano_time();
2056     RIL_CellInfo ci[1] =
2057     {
2058         { // ci[0]
2059             1, // cellInfoType
2060             1, // registered
2061             RIL_TIMESTAMP_TYPE_MODEM,
2062             curTime - 1000, // Fake some time in the past
2063             { // union CellInfo
2064                 {  // RIL_CellInfoGsm gsm
2065                     {  // gsm.cellIdneityGsm
2066                         s_mcc, // mcc
2067                         s_mnc, // mnc
2068                         s_lac, // lac
2069                         s_cid, // cid
2070                     },
2071                     {  // gsm.signalStrengthGsm
2072                         10, // signalStrength
2073                         0  // bitErrorRate
2074                     }
2075                 }
2076             }
2077         }
2078     };
2079
2080     RIL_onRequestComplete(t, RIL_E_SUCCESS, ci, sizeof(ci));
2081 }
2082
2083
2084 static void requestSetCellInfoListRate(void *data, size_t datalen __unused, RIL_Token t)
2085 {
2086     // For now we'll save the rate but no RIL_UNSOL_CELL_INFO_LIST messages
2087     // will be sent.
2088     assert (datalen == sizeof(int));
2089     s_cell_info_rate_ms = ((int *)data)[0];
2090
2091     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2092 }
2093
2094 static void requestGetHardwareConfig(void *data, size_t datalen, RIL_Token t)
2095 {
2096    // TODO - hook this up with real query/info from radio.
2097
2098    RIL_HardwareConfig hwCfg;
2099
2100    RIL_UNUSED_PARM(data);
2101    RIL_UNUSED_PARM(datalen);
2102
2103    hwCfg.type = -1;
2104
2105    RIL_onRequestComplete(t, RIL_E_SUCCESS, &hwCfg, sizeof(hwCfg));
2106 }
2107
2108
2109 /*** Callback methods from the RIL library to us ***/
2110
2111 /**
2112  * Call from RIL to us to make a RIL_REQUEST
2113  *
2114  * Must be completed with a call to RIL_onRequestComplete()
2115  *
2116  * RIL_onRequestComplete() may be called from any thread, before or after
2117  * this function returns.
2118  *
2119  * Because onRequest function could be called from multiple different thread,
2120  * we must ensure that the underlying at_send_command_* function
2121  * is atomic.
2122  */
2123 static void
2124 onRequest (int request, void *data, size_t datalen, RIL_Token t)
2125 {
2126     ATResponse *p_response;
2127     int err;
2128
2129     RLOGD("onRequest: %s", requestToString(request));
2130
2131     /* Ignore all requests except RIL_REQUEST_GET_SIM_STATUS
2132      * when RADIO_STATE_UNAVAILABLE.
2133      */
2134     if (sState == RADIO_STATE_UNAVAILABLE
2135         && request != RIL_REQUEST_GET_SIM_STATUS
2136     ) {
2137         RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
2138         return;
2139     }
2140
2141     /* Ignore all non-power requests when RADIO_STATE_OFF
2142      * (except RIL_REQUEST_GET_SIM_STATUS)
2143      */
2144     if (sState == RADIO_STATE_OFF
2145         && !(request == RIL_REQUEST_RADIO_POWER
2146             || request == RIL_REQUEST_GET_SIM_STATUS)
2147     ) {
2148         RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
2149         return;
2150     }
2151
2152     switch (request) {
2153         case RIL_REQUEST_GET_SIM_STATUS: {
2154             RIL_CardStatus_v6 *p_card_status;
2155             char *p_buffer;
2156             int buffer_size;
2157
2158             int result = getCardStatus(&p_card_status);
2159             if (result == RIL_E_SUCCESS) {
2160                 p_buffer = (char *)p_card_status;
2161                 buffer_size = sizeof(*p_card_status);
2162             } else {
2163                 p_buffer = NULL;
2164                 buffer_size = 0;
2165             }
2166             RIL_onRequestComplete(t, result, p_buffer, buffer_size);
2167             freeCardStatus(p_card_status);
2168             break;
2169         }
2170         case RIL_REQUEST_GET_CURRENT_CALLS:
2171             requestGetCurrentCalls(data, datalen, t);
2172             break;
2173         case RIL_REQUEST_DIAL:
2174             requestDial(data, datalen, t);
2175             break;
2176         case RIL_REQUEST_HANGUP:
2177             requestHangup(data, datalen, t);
2178             break;
2179         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
2180             // 3GPP 22.030 6.5.5
2181             // "Releases all held calls or sets User Determined User Busy
2182             //  (UDUB) for a waiting call."
2183             at_send_command("AT+CHLD=0", NULL);
2184
2185             /* success or failure is ignored by the upper layer here.
2186                it will call GET_CURRENT_CALLS and determine success that way */
2187             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2188             break;
2189         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
2190             // 3GPP 22.030 6.5.5
2191             // "Releases all active calls (if any exist) and accepts
2192             //  the other (held or waiting) call."
2193             at_send_command("AT+CHLD=1", NULL);
2194
2195             /* success or failure is ignored by the upper layer here.
2196                it will call GET_CURRENT_CALLS and determine success that way */
2197             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2198             break;
2199         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
2200             // 3GPP 22.030 6.5.5
2201             // "Places all active calls (if any exist) on hold and accepts
2202             //  the other (held or waiting) call."
2203             at_send_command("AT+CHLD=2", NULL);
2204
2205 #ifdef WORKAROUND_ERRONEOUS_ANSWER
2206             s_expectAnswer = 1;
2207 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
2208
2209             /* success or failure is ignored by the upper layer here.
2210                it will call GET_CURRENT_CALLS and determine success that way */
2211             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2212             break;
2213         case RIL_REQUEST_ANSWER:
2214             at_send_command("ATA", NULL);
2215
2216 #ifdef WORKAROUND_ERRONEOUS_ANSWER
2217             s_expectAnswer = 1;
2218 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
2219
2220             /* success or failure is ignored by the upper layer here.
2221                it will call GET_CURRENT_CALLS and determine success that way */
2222             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2223             break;
2224         case RIL_REQUEST_CONFERENCE:
2225             // 3GPP 22.030 6.5.5
2226             // "Adds a held call to the conversation"
2227             at_send_command("AT+CHLD=3", NULL);
2228
2229             /* success or failure is ignored by the upper layer here.
2230                it will call GET_CURRENT_CALLS and determine success that way */
2231             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2232             break;
2233         case RIL_REQUEST_UDUB:
2234             /* user determined user busy */
2235             /* sometimes used: ATH */
2236             at_send_command("ATH", NULL);
2237
2238             /* success or failure is ignored by the upper layer here.
2239                it will call GET_CURRENT_CALLS and determine success that way */
2240             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2241             break;
2242
2243         case RIL_REQUEST_SEPARATE_CONNECTION:
2244             {
2245                 char  cmd[12];
2246                 int   party = ((int*)data)[0];
2247
2248                 // Make sure that party is in a valid range.
2249                 // (Note: The Telephony middle layer imposes a range of 1 to 7.
2250                 // It's sufficient for us to just make sure it's single digit.)
2251                 if (party > 0 && party < 10) {
2252                     sprintf(cmd, "AT+CHLD=2%d", party);
2253                     at_send_command(cmd, NULL);
2254                     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2255                 } else {
2256                     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2257                 }
2258             }
2259             break;
2260
2261         case RIL_REQUEST_SIGNAL_STRENGTH:
2262             requestSignalStrength(data, datalen, t);
2263             break;
2264         case RIL_REQUEST_VOICE_REGISTRATION_STATE:
2265         case RIL_REQUEST_DATA_REGISTRATION_STATE:
2266             requestRegistrationState(request, data, datalen, t);
2267             break;
2268         case RIL_REQUEST_OPERATOR:
2269             requestOperator(data, datalen, t);
2270             break;
2271         case RIL_REQUEST_RADIO_POWER:
2272             requestRadioPower(data, datalen, t);
2273             break;
2274         case RIL_REQUEST_DTMF: {
2275             char c = ((char *)data)[0];
2276             char *cmd;
2277             asprintf(&cmd, "AT+VTS=%c", (int)c);
2278             at_send_command(cmd, NULL);
2279             free(cmd);
2280             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2281             break;
2282         }
2283         case RIL_REQUEST_SEND_SMS:
2284         case RIL_REQUEST_SEND_SMS_EXPECT_MORE:
2285             requestSendSMS(data, datalen, t);
2286             break;
2287         case RIL_REQUEST_CDMA_SEND_SMS:
2288             requestCdmaSendSMS(data, datalen, t);
2289             break;
2290         case RIL_REQUEST_IMS_SEND_SMS:
2291             requestImsSendSMS(data, datalen, t);
2292             break;
2293         case RIL_REQUEST_SIM_OPEN_CHANNEL:
2294             requestSimOpenChannel(data, datalen, t);
2295             break;
2296         case RIL_REQUEST_SIM_CLOSE_CHANNEL:
2297             requestSimCloseChannel(data, datalen, t);
2298             break;
2299         case RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL:
2300             requestSimTransmitApduChannel(data, datalen, t);
2301             break;
2302         case RIL_REQUEST_SETUP_DATA_CALL:
2303             requestSetupDataCall(data, datalen, t);
2304             break;
2305         case RIL_REQUEST_SMS_ACKNOWLEDGE:
2306             requestSMSAcknowledge(data, datalen, t);
2307             break;
2308
2309         case RIL_REQUEST_GET_IMSI:
2310             p_response = NULL;
2311             err = at_send_command_numeric("AT+CIMI", &p_response);
2312
2313             if (err < 0 || p_response->success == 0) {
2314                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2315             } else {
2316                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
2317                     p_response->p_intermediates->line, sizeof(char *));
2318             }
2319             at_response_free(p_response);
2320             break;
2321
2322         case RIL_REQUEST_GET_IMEI:
2323             p_response = NULL;
2324             err = at_send_command_numeric("AT+CGSN", &p_response);
2325
2326             if (err < 0 || p_response->success == 0) {
2327                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2328             } else {
2329                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
2330                     p_response->p_intermediates->line, sizeof(char *));
2331             }
2332             at_response_free(p_response);
2333             break;
2334
2335         case RIL_REQUEST_SIM_IO:
2336             requestSIM_IO(data,datalen,t);
2337             break;
2338
2339         case RIL_REQUEST_SEND_USSD:
2340             requestSendUSSD(data, datalen, t);
2341             break;
2342
2343         case RIL_REQUEST_CANCEL_USSD:
2344             p_response = NULL;
2345             err = at_send_command_numeric("AT+CUSD=2", &p_response);
2346
2347             if (err < 0 || p_response->success == 0) {
2348                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2349             } else {
2350                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
2351                     p_response->p_intermediates->line, sizeof(char *));
2352             }
2353             at_response_free(p_response);
2354             break;
2355
2356         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
2357             at_send_command("AT+COPS=0", NULL);
2358             break;
2359
2360         case RIL_REQUEST_DATA_CALL_LIST:
2361             requestDataCallList(data, datalen, t);
2362             break;
2363
2364         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
2365             requestQueryNetworkSelectionMode(data, datalen, t);
2366             break;
2367
2368         case RIL_REQUEST_OEM_HOOK_RAW:
2369             // echo back data
2370             RIL_onRequestComplete(t, RIL_E_SUCCESS, data, datalen);
2371             break;
2372
2373
2374         case RIL_REQUEST_OEM_HOOK_STRINGS: {
2375             int i;
2376             const char ** cur;
2377
2378             RLOGD("got OEM_HOOK_STRINGS: 0x%8p %lu", data, (long)datalen);
2379
2380
2381             for (i = (datalen / sizeof (char *)), cur = (const char **)data ;
2382                     i > 0 ; cur++, i --) {
2383                 RLOGD("> '%s'", *cur);
2384             }
2385
2386             // echo back strings
2387             RIL_onRequestComplete(t, RIL_E_SUCCESS, data, datalen);
2388             break;
2389         }
2390
2391         case RIL_REQUEST_WRITE_SMS_TO_SIM:
2392             requestWriteSmsToSim(data, datalen, t);
2393             break;
2394
2395         case RIL_REQUEST_DELETE_SMS_ON_SIM: {
2396             char * cmd;
2397             p_response = NULL;
2398             asprintf(&cmd, "AT+CMGD=%d", ((int *)data)[0]);
2399             err = at_send_command(cmd, &p_response);
2400             free(cmd);
2401             if (err < 0 || p_response->success == 0) {
2402                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2403             } else {
2404                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2405             }
2406             at_response_free(p_response);
2407             break;
2408         }
2409
2410         case RIL_REQUEST_ENTER_SIM_PIN:
2411         case RIL_REQUEST_ENTER_SIM_PUK:
2412         case RIL_REQUEST_ENTER_SIM_PIN2:
2413         case RIL_REQUEST_ENTER_SIM_PUK2:
2414         case RIL_REQUEST_CHANGE_SIM_PIN:
2415         case RIL_REQUEST_CHANGE_SIM_PIN2:
2416             requestEnterSimPin(data, datalen, t);
2417             break;
2418
2419         case RIL_REQUEST_IMS_REGISTRATION_STATE: {
2420             int reply[2];
2421             //0==unregistered, 1==registered
2422             reply[0] = s_ims_registered;
2423
2424             //to be used when changed to include service supporated info
2425             //reply[1] = s_ims_services;
2426
2427             // FORMAT_3GPP(1) vs FORMAT_3GPP2(2);
2428             reply[1] = s_ims_format;
2429
2430             RLOGD("IMS_REGISTRATION=%d, format=%d ",
2431                     reply[0], reply[1]);
2432             if (reply[1] != -1) {
2433                 RIL_onRequestComplete(t, RIL_E_SUCCESS, reply, sizeof(reply));
2434             } else {
2435                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2436             }
2437             break;
2438         }
2439
2440         case RIL_REQUEST_VOICE_RADIO_TECH:
2441             {
2442                 int tech = techFromModemType(TECH(sMdmInfo));
2443                 if (tech < 0 )
2444                     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2445                 else
2446                     RIL_onRequestComplete(t, RIL_E_SUCCESS, &tech, sizeof(tech));
2447             }
2448             break;
2449         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
2450             requestSetPreferredNetworkType(request, data, datalen, t);
2451             break;
2452
2453         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
2454             requestGetPreferredNetworkType(request, data, datalen, t);
2455             break;
2456
2457         case RIL_REQUEST_GET_CELL_INFO_LIST:
2458             requestGetCellInfoList(data, datalen, t);
2459             break;
2460
2461         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
2462             requestSetCellInfoListRate(data, datalen, t);
2463             break;
2464
2465         case RIL_REQUEST_GET_HARDWARE_CONFIG:
2466             requestGetHardwareConfig(data, datalen, t);
2467             break;
2468
2469         case RIL_REQUEST_SHUTDOWN:
2470             requestShutdown(t);
2471             break;
2472
2473         /* CDMA Specific Requests */
2474         case RIL_REQUEST_BASEBAND_VERSION:
2475             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2476                 requestCdmaBaseBandVersion(request, data, datalen, t);
2477                 break;
2478             } // Fall-through if tech is not cdma
2479
2480         case RIL_REQUEST_DEVICE_IDENTITY:
2481             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2482                 requestCdmaDeviceIdentity(request, data, datalen, t);
2483                 break;
2484             } // Fall-through if tech is not cdma
2485
2486         case RIL_REQUEST_CDMA_SUBSCRIPTION:
2487             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2488                 requestCdmaSubscription(request, data, datalen, t);
2489                 break;
2490             } // Fall-through if tech is not cdma
2491
2492         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
2493             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2494                 requestCdmaSetSubscriptionSource(request, data, datalen, t);
2495                 break;
2496             } // Fall-through if tech is not cdma
2497
2498         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
2499             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2500                 requestCdmaGetSubscriptionSource(request, data, datalen, t);
2501                 break;
2502             } // Fall-through if tech is not cdma
2503
2504         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:
2505             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2506                 requestCdmaGetRoamingPreference(request, data, datalen, t);
2507                 break;
2508             } // Fall-through if tech is not cdma
2509
2510         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
2511             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2512                 requestCdmaSetRoamingPreference(request, data, datalen, t);
2513                 break;
2514             } // Fall-through if tech is not cdma
2515
2516         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
2517             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2518                 requestExitEmergencyMode(data, datalen, t);
2519                 break;
2520             } // Fall-through if tech is not cdma
2521
2522         default:
2523             RLOGD("Request not supported. Tech: %d",TECH(sMdmInfo));
2524             RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
2525             break;
2526     }
2527 }
2528
2529 /**
2530  * Synchronous call from the RIL to us to return current radio state.
2531  * RADIO_STATE_UNAVAILABLE should be the initial state.
2532  */
2533 static RIL_RadioState
2534 currentState()
2535 {
2536     return sState;
2537 }
2538 /**
2539  * Call from RIL to us to find out whether a specific request code
2540  * is supported by this implementation.
2541  *
2542  * Return 1 for "supported" and 0 for "unsupported"
2543  */
2544
2545 static int
2546 onSupports (int requestCode __unused)
2547 {
2548     //@@@ todo
2549
2550     return 1;
2551 }
2552
2553 static void onCancel (RIL_Token t __unused)
2554 {
2555     //@@@todo
2556
2557 }
2558
2559 static const char * getVersion(void)
2560 {
2561     return "android reference-ril 1.0";
2562 }
2563
2564 static void
2565 setRadioTechnology(ModemInfo *mdm, int newtech)
2566 {
2567     RLOGD("setRadioTechnology(%d)", newtech);
2568
2569     int oldtech = TECH(mdm);
2570
2571     if (newtech != oldtech) {
2572         RLOGD("Tech change (%d => %d)", oldtech, newtech);
2573         TECH(mdm) = newtech;
2574         if (techFromModemType(newtech) != techFromModemType(oldtech)) {
2575             int tech = techFromModemType(TECH(sMdmInfo));
2576             if (tech > 0 ) {
2577                 RIL_onUnsolicitedResponse(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
2578                                           &tech, sizeof(tech));
2579             }
2580         }
2581     }
2582 }
2583
2584 static void
2585 setRadioState(RIL_RadioState newState)
2586 {
2587     RLOGD("setRadioState(%d)", newState);
2588     RIL_RadioState oldState;
2589
2590     pthread_mutex_lock(&s_state_mutex);
2591
2592     oldState = sState;
2593
2594     if (s_closed > 0) {
2595         // If we're closed, the only reasonable state is
2596         // RADIO_STATE_UNAVAILABLE
2597         // This is here because things on the main thread
2598         // may attempt to change the radio state after the closed
2599         // event happened in another thread
2600         newState = RADIO_STATE_UNAVAILABLE;
2601     }
2602
2603     if (sState != newState || s_closed > 0) {
2604         sState = newState;
2605
2606         pthread_cond_broadcast (&s_state_cond);
2607     }
2608
2609     pthread_mutex_unlock(&s_state_mutex);
2610
2611
2612     /* do these outside of the mutex */
2613     if (sState != oldState) {
2614         RIL_onUnsolicitedResponse (RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
2615                                     NULL, 0);
2616         // Sim state can change as result of radio state change
2617         RIL_onUnsolicitedResponse (RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED,
2618                                     NULL, 0);
2619
2620         /* FIXME onSimReady() and onRadioPowerOn() cannot be called
2621          * from the AT reader thread
2622          * Currently, this doesn't happen, but if that changes then these
2623          * will need to be dispatched on the request thread
2624          */
2625         if (sState == RADIO_STATE_ON) {
2626             onRadioPowerOn();
2627         }
2628     }
2629 }
2630
2631 /** Returns RUIM_NOT_READY on error */
2632 static SIM_Status
2633 getRUIMStatus()
2634 {
2635     ATResponse *p_response = NULL;
2636     int err;
2637     int ret;
2638     char *cpinLine;
2639     char *cpinResult;
2640
2641     if (sState == RADIO_STATE_OFF || sState == RADIO_STATE_UNAVAILABLE) {
2642         ret = SIM_NOT_READY;
2643         goto done;
2644     }
2645
2646     err = at_send_command_singleline("AT+CPIN?", "+CPIN:", &p_response);
2647
2648     if (err != 0) {
2649         ret = SIM_NOT_READY;
2650         goto done;
2651     }
2652
2653     switch (at_get_cme_error(p_response)) {
2654         case CME_SUCCESS:
2655             break;
2656
2657         case CME_SIM_NOT_INSERTED:
2658             ret = SIM_ABSENT;
2659             goto done;
2660
2661         default:
2662             ret = SIM_NOT_READY;
2663             goto done;
2664     }
2665
2666     /* CPIN? has succeeded, now look at the result */
2667
2668     cpinLine = p_response->p_intermediates->line;
2669     err = at_tok_start (&cpinLine);
2670
2671     if (err < 0) {
2672         ret = SIM_NOT_READY;
2673         goto done;
2674     }
2675
2676     err = at_tok_nextstr(&cpinLine, &cpinResult);
2677
2678     if (err < 0) {
2679         ret = SIM_NOT_READY;
2680         goto done;
2681     }
2682
2683     if (0 == strcmp (cpinResult, "SIM PIN")) {
2684         ret = SIM_PIN;
2685         goto done;
2686     } else if (0 == strcmp (cpinResult, "SIM PUK")) {
2687         ret = SIM_PUK;
2688         goto done;
2689     } else if (0 == strcmp (cpinResult, "PH-NET PIN")) {
2690         return SIM_NETWORK_PERSONALIZATION;
2691     } else if (0 != strcmp (cpinResult, "READY"))  {
2692         /* we're treating unsupported lock types as "sim absent" */
2693         ret = SIM_ABSENT;
2694         goto done;
2695     }
2696
2697     at_response_free(p_response);
2698     p_response = NULL;
2699     cpinResult = NULL;
2700
2701     ret = SIM_READY;
2702
2703 done:
2704     at_response_free(p_response);
2705     return ret;
2706 }
2707
2708 /** Returns SIM_NOT_READY on error */
2709 static SIM_Status
2710 getSIMStatus()
2711 {
2712     ATResponse *p_response = NULL;
2713     int err;
2714     int ret;
2715     char *cpinLine;
2716     char *cpinResult;
2717
2718     RLOGD("getSIMStatus(). sState: %d",sState);
2719     if (sState == RADIO_STATE_OFF || sState == RADIO_STATE_UNAVAILABLE) {
2720         ret = SIM_NOT_READY;
2721         goto done;
2722     }
2723
2724     err = at_send_command_singleline("AT+CPIN?", "+CPIN:", &p_response);
2725
2726     if (err != 0) {
2727         ret = SIM_NOT_READY;
2728         goto done;
2729     }
2730
2731     switch (at_get_cme_error(p_response)) {
2732         case CME_SUCCESS:
2733             break;
2734
2735         case CME_SIM_NOT_INSERTED:
2736             ret = SIM_ABSENT;
2737             goto done;
2738
2739         default:
2740             ret = SIM_NOT_READY;
2741             goto done;
2742     }
2743
2744     /* CPIN? has succeeded, now look at the result */
2745
2746     cpinLine = p_response->p_intermediates->line;
2747     err = at_tok_start (&cpinLine);
2748
2749     if (err < 0) {
2750         ret = SIM_NOT_READY;
2751         goto done;
2752     }
2753
2754     err = at_tok_nextstr(&cpinLine, &cpinResult);
2755
2756     if (err < 0) {
2757         ret = SIM_NOT_READY;
2758         goto done;
2759     }
2760
2761     if (0 == strcmp (cpinResult, "SIM PIN")) {
2762         ret = SIM_PIN;
2763         goto done;
2764     } else if (0 == strcmp (cpinResult, "SIM PUK")) {
2765         ret = SIM_PUK;
2766         goto done;
2767     } else if (0 == strcmp (cpinResult, "PH-NET PIN")) {
2768         return SIM_NETWORK_PERSONALIZATION;
2769     } else if (0 != strcmp (cpinResult, "READY"))  {
2770         /* we're treating unsupported lock types as "sim absent" */
2771         ret = SIM_ABSENT;
2772         goto done;
2773     }
2774
2775     at_response_free(p_response);
2776     p_response = NULL;
2777     cpinResult = NULL;
2778
2779     ret = SIM_READY;
2780
2781 done:
2782     at_response_free(p_response);
2783     return ret;
2784 }
2785
2786
2787 /**
2788  * Get the current card status.
2789  *
2790  * This must be freed using freeCardStatus.
2791  * @return: On success returns RIL_E_SUCCESS
2792  */
2793 static int getCardStatus(RIL_CardStatus_v6 **pp_card_status) {
2794     static RIL_AppStatus app_status_array[] = {
2795         // SIM_ABSENT = 0
2796         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
2797           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2798         // SIM_NOT_READY = 1
2799         { RIL_APPTYPE_SIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
2800           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2801         // SIM_READY = 2
2802         { RIL_APPTYPE_SIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
2803           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2804         // SIM_PIN = 3
2805         { RIL_APPTYPE_SIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
2806           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
2807         // SIM_PUK = 4
2808         { RIL_APPTYPE_SIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
2809           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
2810         // SIM_NETWORK_PERSONALIZATION = 5
2811         { RIL_APPTYPE_SIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
2812           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
2813         // RUIM_ABSENT = 6
2814         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
2815           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2816         // RUIM_NOT_READY = 7
2817         { RIL_APPTYPE_RUIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
2818           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2819         // RUIM_READY = 8
2820         { RIL_APPTYPE_RUIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
2821           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2822         // RUIM_PIN = 9
2823         { RIL_APPTYPE_RUIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
2824           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
2825         // RUIM_PUK = 10
2826         { RIL_APPTYPE_RUIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
2827           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
2828         // RUIM_NETWORK_PERSONALIZATION = 11
2829         { RIL_APPTYPE_RUIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
2830            NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN }
2831     };
2832     RIL_CardState card_state;
2833     int num_apps;
2834
2835     int sim_status = getSIMStatus();
2836     if (sim_status == SIM_ABSENT) {
2837         card_state = RIL_CARDSTATE_ABSENT;
2838         num_apps = 0;
2839     } else {
2840         card_state = RIL_CARDSTATE_PRESENT;
2841         num_apps = 2;
2842     }
2843
2844     // Allocate and initialize base card status.
2845     RIL_CardStatus_v6 *p_card_status = malloc(sizeof(RIL_CardStatus_v6));
2846     p_card_status->card_state = card_state;
2847     p_card_status->universal_pin_state = RIL_PINSTATE_UNKNOWN;
2848     p_card_status->gsm_umts_subscription_app_index = -1;
2849     p_card_status->cdma_subscription_app_index = -1;
2850     p_card_status->ims_subscription_app_index = -1;
2851     p_card_status->num_applications = num_apps;
2852
2853     // Initialize application status
2854     int i;
2855     for (i = 0; i < RIL_CARD_MAX_APPS; i++) {
2856         p_card_status->applications[i] = app_status_array[SIM_ABSENT];
2857     }
2858
2859     // Pickup the appropriate application status
2860     // that reflects sim_status for gsm.
2861     if (num_apps != 0) {
2862         // Only support one app, gsm
2863         p_card_status->num_applications = 2;
2864         p_card_status->gsm_umts_subscription_app_index = 0;
2865         p_card_status->cdma_subscription_app_index = 1;
2866
2867         // Get the correct app status
2868         p_card_status->applications[0] = app_status_array[sim_status];
2869         p_card_status->applications[1] = app_status_array[sim_status + RUIM_ABSENT];
2870     }
2871
2872     *pp_card_status = p_card_status;
2873     return RIL_E_SUCCESS;
2874 }
2875
2876 /**
2877  * Free the card status returned by getCardStatus
2878  */
2879 static void freeCardStatus(RIL_CardStatus_v6 *p_card_status) {
2880     free(p_card_status);
2881 }
2882
2883 /**
2884  * SIM ready means any commands that access the SIM will work, including:
2885  *  AT+CPIN, AT+CSMS, AT+CNMI, AT+CRSM
2886  *  (all SMS-related commands)
2887  */
2888
2889 static void pollSIMState (void *param __unused)
2890 {
2891     ATResponse *p_response;
2892     int ret;
2893
2894     if (sState != RADIO_STATE_UNAVAILABLE) {
2895         // no longer valid to poll
2896         return;
2897     }
2898
2899     switch(getSIMStatus()) {
2900         case SIM_ABSENT:
2901         case SIM_PIN:
2902         case SIM_PUK:
2903         case SIM_NETWORK_PERSONALIZATION:
2904         default:
2905             RLOGI("SIM ABSENT or LOCKED");
2906             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
2907         return;
2908
2909         case SIM_NOT_READY:
2910             RIL_requestTimedCallback (pollSIMState, NULL, &TIMEVAL_SIMPOLL);
2911         return;
2912
2913         case SIM_READY:
2914             RLOGI("SIM_READY");
2915             onSIMReady();
2916             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
2917         return;
2918     }
2919 }
2920
2921 /** returns 1 if on, 0 if off, and -1 on error */
2922 static int isRadioOn()
2923 {
2924     ATResponse *p_response = NULL;
2925     int err;
2926     char *line;
2927     char ret;
2928
2929     err = at_send_command_singleline("AT+CFUN?", "+CFUN:", &p_response);
2930
2931     if (err < 0 || p_response->success == 0) {
2932         // assume radio is off
2933         goto error;
2934     }
2935
2936     line = p_response->p_intermediates->line;
2937
2938     err = at_tok_start(&line);
2939     if (err < 0) goto error;
2940
2941     err = at_tok_nextbool(&line, &ret);
2942     if (err < 0) goto error;
2943
2944     at_response_free(p_response);
2945
2946     return (int)ret;
2947
2948 error:
2949
2950     at_response_free(p_response);
2951     return -1;
2952 }
2953
2954 /**
2955  * Parse the response generated by a +CTEC AT command
2956  * The values read from the response are stored in current and preferred.
2957  * Both current and preferred may be null. The corresponding value is ignored in that case.
2958  *
2959  * @return: -1 if some error occurs (or if the modem doesn't understand the +CTEC command)
2960  *          1 if the response includes the current technology only
2961  *          0 if the response includes both current technology and preferred mode
2962  */
2963 int parse_technology_response( const char *response, int *current, int32_t *preferred )
2964 {
2965     int err;
2966     char *line, *p;
2967     int ct;
2968     int32_t pt = 0;
2969     char *str_pt;
2970
2971     line = p = strdup(response);
2972     RLOGD("Response: %s", line);
2973     err = at_tok_start(&p);
2974     if (err || !at_tok_hasmore(&p)) {
2975         RLOGD("err: %d. p: %s", err, p);
2976         free(line);
2977         return -1;
2978     }
2979
2980     err = at_tok_nextint(&p, &ct);
2981     if (err) {
2982         free(line);
2983         return -1;
2984     }
2985     if (current) *current = ct;
2986
2987     RLOGD("line remaining after int: %s", p);
2988
2989     err = at_tok_nexthexint(&p, &pt);
2990     if (err) {
2991         free(line);
2992         return 1;
2993     }
2994     if (preferred) {
2995         *preferred = pt;
2996     }
2997     free(line);
2998
2999     return 0;
3000 }
3001
3002 int query_supported_techs( ModemInfo *mdm __unused, int *supported )
3003 {
3004     ATResponse *p_response;
3005     int err, val, techs = 0;
3006     char *tok;
3007     char *line;
3008
3009     RLOGD("query_supported_techs");
3010     err = at_send_command_singleline("AT+CTEC=?", "+CTEC:", &p_response);
3011     if (err || !p_response->success)
3012         goto error;
3013     line = p_response->p_intermediates->line;
3014     err = at_tok_start(&line);
3015     if (err || !at_tok_hasmore(&line))
3016         goto error;
3017     while (!at_tok_nextint(&line, &val)) {
3018         techs |= ( 1 << val );
3019     }
3020     if (supported) *supported = techs;
3021     return 0;
3022 error:
3023     at_response_free(p_response);
3024     return -1;
3025 }
3026
3027 /**
3028  * query_ctec. Send the +CTEC AT command to the modem to query the current
3029  * and preferred modes. It leaves values in the addresses pointed to by
3030  * current and preferred. If any of those pointers are NULL, the corresponding value
3031  * is ignored, but the return value will still reflect if retreiving and parsing of the
3032  * values suceeded.
3033  *
3034  * @mdm Currently unused
3035  * @current A pointer to store the current mode returned by the modem. May be null.
3036  * @preferred A pointer to store the preferred mode returned by the modem. May be null.
3037  * @return -1 on error (or failure to parse)
3038  *         1 if only the current mode was returned by modem (or failed to parse preferred)
3039  *         0 if both current and preferred were returned correctly
3040  */
3041 int query_ctec(ModemInfo *mdm __unused, int *current, int32_t *preferred)
3042 {
3043     ATResponse *response = NULL;
3044     int err;
3045     int res;
3046
3047     RLOGD("query_ctec. current: %p, preferred: %p", current, preferred);
3048     err = at_send_command_singleline("AT+CTEC?", "+CTEC:", &response);
3049     if (!err && response->success) {
3050         res = parse_technology_response(response->p_intermediates->line, current, preferred);
3051         at_response_free(response);
3052         return res;
3053     }
3054     RLOGE("Error executing command: %d. response: %p. status: %d", err, response, response? response->success : -1);
3055     at_response_free(response);
3056     return -1;
3057 }
3058
3059 int is_multimode_modem(ModemInfo *mdm)
3060 {
3061     ATResponse *response;
3062     int err;
3063     char *line;
3064     int tech;
3065     int32_t preferred;
3066
3067     if (query_ctec(mdm, &tech, &preferred) == 0) {
3068         mdm->currentTech = tech;
3069         mdm->preferredNetworkMode = preferred;
3070         if (query_supported_techs(mdm, &mdm->supportedTechs)) {
3071             return 0;
3072         }
3073         return 1;
3074     }
3075     return 0;
3076 }
3077
3078 /**
3079  * Find out if our modem is GSM, CDMA or both (Multimode)
3080  */
3081 static void probeForModemMode(ModemInfo *info)
3082 {
3083     ATResponse *response;
3084     int err;
3085     assert (info);
3086     // Currently, our only known multimode modem is qemu's android modem,
3087     // which implements the AT+CTEC command to query and set mode.
3088     // Try that first
3089
3090     if (is_multimode_modem(info)) {
3091         RLOGI("Found Multimode Modem. Supported techs mask: %8.8x. Current tech: %d",
3092             info->supportedTechs, info->currentTech);
3093         return;
3094     }
3095
3096     /* Being here means that our modem is not multimode */
3097     info->isMultimode = 0;
3098
3099     /* CDMA Modems implement the AT+WNAM command */
3100     err = at_send_command_singleline("AT+WNAM","+WNAM:", &response);
3101     if (!err && response->success) {
3102         at_response_free(response);
3103         // TODO: find out if we really support EvDo
3104         info->supportedTechs = MDM_CDMA | MDM_EVDO;
3105         info->currentTech = MDM_CDMA;
3106         RLOGI("Found CDMA Modem");
3107         return;
3108     }
3109     if (!err) at_response_free(response);
3110     // TODO: find out if modem really supports WCDMA/LTE
3111     info->supportedTechs = MDM_GSM | MDM_WCDMA | MDM_LTE;
3112     info->currentTech = MDM_GSM;
3113     RLOGI("Found GSM Modem");
3114 }
3115
3116 /**
3117  * Initialize everything that can be configured while we're still in
3118  * AT+CFUN=0
3119  */
3120 static void initializeCallback(void *param __unused)
3121 {
3122     ATResponse *p_response = NULL;
3123     int err;
3124
3125     setRadioState (RADIO_STATE_OFF);
3126
3127     at_handshake();
3128
3129     probeForModemMode(sMdmInfo);
3130     /* note: we don't check errors here. Everything important will
3131        be handled in onATTimeout and onATReaderClosed */
3132
3133     /*  atchannel is tolerant of echo but it must */
3134     /*  have verbose result codes */
3135     at_send_command("ATE0Q0V1", NULL);
3136
3137     /*  No auto-answer */
3138     at_send_command("ATS0=0", NULL);
3139
3140     /*  Extended errors */
3141     at_send_command("AT+CMEE=1", NULL);
3142
3143     /*  Network registration events */
3144     err = at_send_command("AT+CREG=2", &p_response);
3145
3146     /* some handsets -- in tethered mode -- don't support CREG=2 */
3147     if (err < 0 || p_response->success == 0) {
3148         at_send_command("AT+CREG=1", NULL);
3149     }
3150
3151     at_response_free(p_response);
3152
3153     /*  GPRS registration events */
3154     at_send_command("AT+CGREG=1", NULL);
3155
3156     /*  Call Waiting notifications */
3157     at_send_command("AT+CCWA=1", NULL);
3158
3159     /*  Alternating voice/data off */
3160     at_send_command("AT+CMOD=0", NULL);
3161
3162     /*  Not muted */
3163     at_send_command("AT+CMUT=0", NULL);
3164
3165     /*  +CSSU unsolicited supp service notifications */
3166     at_send_command("AT+CSSN=0,1", NULL);
3167
3168     /*  no connected line identification */
3169     at_send_command("AT+COLP=0", NULL);
3170
3171     /*  HEX character set */
3172     at_send_command("AT+CSCS=\"HEX\"", NULL);
3173
3174     /*  USSD unsolicited */
3175     at_send_command("AT+CUSD=1", NULL);
3176
3177     /*  Enable +CGEV GPRS event notifications, but don't buffer */
3178     at_send_command("AT+CGEREP=1,0", NULL);
3179
3180     /*  SMS PDU mode */
3181     at_send_command("AT+CMGF=0", NULL);
3182
3183 #ifdef USE_TI_COMMANDS
3184
3185     at_send_command("AT%CPI=3", NULL);
3186
3187     /*  TI specific -- notifications when SMS is ready (currently ignored) */
3188     at_send_command("AT%CSTAT=1", NULL);
3189
3190 #endif /* USE_TI_COMMANDS */
3191
3192
3193     /* assume radio is off on error */
3194     if (isRadioOn() > 0) {
3195         setRadioState (RADIO_STATE_ON);
3196     }
3197 }
3198
3199 static void waitForClose()
3200 {
3201     pthread_mutex_lock(&s_state_mutex);
3202
3203     while (s_closed == 0) {
3204         pthread_cond_wait(&s_state_cond, &s_state_mutex);
3205     }
3206
3207     pthread_mutex_unlock(&s_state_mutex);
3208 }
3209
3210 static void sendUnsolImsNetworkStateChanged()
3211 {
3212 #if 0 // to be used when unsol is changed to return data.
3213     int reply[2];
3214     reply[0] = s_ims_registered;
3215     reply[1] = s_ims_services;
3216     reply[1] = s_ims_format;
3217 #endif
3218     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED,
3219             NULL, 0);
3220 }
3221
3222 /**
3223  * Called by atchannel when an unsolicited line appears
3224  * This is called on atchannel's reader thread. AT commands may
3225  * not be issued here
3226  */
3227 static void onUnsolicited (const char *s, const char *sms_pdu)
3228 {
3229     char *line = NULL, *p;
3230     int err;
3231
3232     /* Ignore unsolicited responses until we're initialized.
3233      * This is OK because the RIL library will poll for initial state
3234      */
3235     if (sState == RADIO_STATE_UNAVAILABLE) {
3236         return;
3237     }
3238
3239     if (strStartsWith(s, "%CTZV:")) {
3240         /* TI specific -- NITZ time */
3241         char *response;
3242
3243         line = p = strdup(s);
3244         at_tok_start(&p);
3245
3246         err = at_tok_nextstr(&p, &response);
3247
3248         if (err != 0) {
3249             RLOGE("invalid NITZ line %s\n", s);
3250         } else {
3251             RIL_onUnsolicitedResponse (
3252                 RIL_UNSOL_NITZ_TIME_RECEIVED,
3253                 response, strlen(response));
3254         }
3255         free(line);
3256     } else if (strStartsWith(s,"+CRING:")
3257                 || strStartsWith(s,"RING")
3258                 || strStartsWith(s,"NO CARRIER")
3259                 || strStartsWith(s,"+CCWA")
3260     ) {
3261         RIL_onUnsolicitedResponse (
3262             RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
3263             NULL, 0);
3264 #ifdef WORKAROUND_FAKE_CGEV
3265         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL); //TODO use new function
3266 #endif /* WORKAROUND_FAKE_CGEV */
3267     } else if (strStartsWith(s,"+CREG:")
3268                 || strStartsWith(s,"+CGREG:")
3269     ) {
3270         RIL_onUnsolicitedResponse (
3271             RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
3272             NULL, 0);
3273 #ifdef WORKAROUND_FAKE_CGEV
3274         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
3275 #endif /* WORKAROUND_FAKE_CGEV */
3276     } else if (strStartsWith(s, "+CMT:")) {
3277         RIL_onUnsolicitedResponse (
3278             RIL_UNSOL_RESPONSE_NEW_SMS,
3279             sms_pdu, strlen(sms_pdu));
3280     } else if (strStartsWith(s, "+CDS:")) {
3281         RIL_onUnsolicitedResponse (
3282             RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT,
3283             sms_pdu, strlen(sms_pdu));
3284     } else if (strStartsWith(s, "+CGEV:")) {
3285         /* Really, we can ignore NW CLASS and ME CLASS events here,
3286          * but right now we don't since extranous
3287          * RIL_UNSOL_DATA_CALL_LIST_CHANGED calls are tolerated
3288          */
3289         /* can't issue AT commands here -- call on main thread */
3290         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
3291 #ifdef WORKAROUND_FAKE_CGEV
3292     } else if (strStartsWith(s, "+CME ERROR: 150")) {
3293         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
3294 #endif /* WORKAROUND_FAKE_CGEV */
3295     } else if (strStartsWith(s, "+CTEC: ")) {
3296         int tech, mask;
3297         switch (parse_technology_response(s, &tech, NULL))
3298         {
3299             case -1: // no argument could be parsed.
3300                 RLOGE("invalid CTEC line %s\n", s);
3301                 break;
3302             case 1: // current mode correctly parsed
3303             case 0: // preferred mode correctly parsed
3304                 mask = 1 << tech;
3305                 if (mask != MDM_GSM && mask != MDM_CDMA &&
3306                      mask != MDM_WCDMA && mask != MDM_LTE) {
3307                     RLOGE("Unknown technology %d\n", tech);
3308                 } else {
3309                     setRadioTechnology(sMdmInfo, tech);
3310                 }
3311                 break;
3312         }
3313     } else if (strStartsWith(s, "+CCSS: ")) {
3314         int source = 0;
3315         line = p = strdup(s);
3316         if (!line) {
3317             RLOGE("+CCSS: Unable to allocate memory");
3318             return;
3319         }
3320         if (at_tok_start(&p) < 0) {
3321             free(line);
3322             return;
3323         }
3324         if (at_tok_nextint(&p, &source) < 0) {
3325             RLOGE("invalid +CCSS response: %s", line);
3326             free(line);
3327             return;
3328         }
3329         SSOURCE(sMdmInfo) = source;
3330         RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
3331                                   &source, sizeof(source));
3332     } else if (strStartsWith(s, "+WSOS: ")) {
3333         char state = 0;
3334         int unsol;
3335         line = p = strdup(s);
3336         if (!line) {
3337             RLOGE("+WSOS: Unable to allocate memory");
3338             return;
3339         }
3340         if (at_tok_start(&p) < 0) {
3341             free(line);
3342             return;
3343         }
3344         if (at_tok_nextbool(&p, &state) < 0) {
3345             RLOGE("invalid +WSOS response: %s", line);
3346             free(line);
3347             return;
3348         }
3349         free(line);
3350
3351         unsol = state ?
3352                 RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE : RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE;
3353
3354         RIL_onUnsolicitedResponse(unsol, NULL, 0);
3355
3356     } else if (strStartsWith(s, "+WPRL: ")) {
3357         int version = -1;
3358         line = p = strdup(s);
3359         if (!line) {
3360             RLOGE("+WPRL: Unable to allocate memory");
3361             return;
3362         }
3363         if (at_tok_start(&p) < 0) {
3364             RLOGE("invalid +WPRL response: %s", s);
3365             free(line);
3366             return;
3367         }
3368         if (at_tok_nextint(&p, &version) < 0) {
3369             RLOGE("invalid +WPRL response: %s", s);
3370             free(line);
3371             return;
3372         }
3373         free(line);
3374         RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_PRL_CHANGED, &version, sizeof(version));
3375     } else if (strStartsWith(s, "+CFUN: 0")) {
3376         setRadioState(RADIO_STATE_OFF);
3377     }
3378 }
3379
3380 /* Called on command or reader thread */
3381 static void onATReaderClosed()
3382 {
3383     RLOGI("AT channel closed\n");
3384     at_close();
3385     s_closed = 1;
3386
3387     setRadioState (RADIO_STATE_UNAVAILABLE);
3388 }
3389
3390 /* Called on command thread */
3391 static void onATTimeout()
3392 {
3393     RLOGI("AT channel timeout; closing\n");
3394     at_close();
3395
3396     s_closed = 1;
3397
3398     /* FIXME cause a radio reset here */
3399
3400     setRadioState (RADIO_STATE_UNAVAILABLE);
3401 }
3402
3403 /* Called to pass hardware configuration information to telephony
3404  * framework.
3405  */
3406 static void setHardwareConfiguration(int num, RIL_HardwareConfig *cfg)
3407 {
3408    RIL_onUnsolicitedResponse(RIL_UNSOL_HARDWARE_CONFIG_CHANGED, cfg, num*sizeof(*cfg));
3409 }
3410
3411 static void usage(char *s __unused)
3412 {
3413 #ifdef RIL_SHLIB
3414     fprintf(stderr, "reference-ril requires: -p <tcp port> or -d /dev/tty_device\n");
3415 #else
3416     fprintf(stderr, "usage: %s [-p <tcp port>] [-d /dev/tty_device]\n", s);
3417     exit(-1);
3418 #endif
3419 }
3420
3421 static void *
3422 mainLoop(void *param __unused)
3423 {
3424     int fd;
3425     int ret;
3426
3427     AT_DUMP("== ", "entering mainLoop()", -1 );
3428     at_set_on_reader_closed(onATReaderClosed);
3429     at_set_on_timeout(onATTimeout);
3430
3431     for (;;) {
3432         fd = -1;
3433         while  (fd < 0) {
3434             if (isInEmulator()) {
3435                 fd = qemu_pipe_open("pipe:qemud:gsm");
3436             } else if (s_port > 0) {
3437                 fd = socket_network_client("localhost", s_port, SOCK_STREAM);
3438             } else if (s_device_socket) {
3439                 fd = socket_local_client(s_device_path,
3440                                          ANDROID_SOCKET_NAMESPACE_FILESYSTEM,
3441                                          SOCK_STREAM);
3442             } else if (s_device_path != NULL) {
3443                 fd = open (s_device_path, O_RDWR);
3444                 if ( fd >= 0 && !memcmp( s_device_path, "/dev/ttyS", 9 ) ) {
3445                     /* disable echo on serial ports */
3446                     struct termios  ios;
3447                     tcgetattr( fd, &ios );
3448                     ios.c_lflag = 0;  /* disable ECHO, ICANON, etc... */
3449                     tcsetattr( fd, TCSANOW, &ios );
3450                 }
3451             }
3452
3453             if (fd < 0) {
3454                 perror ("opening AT interface. retrying...");
3455                 sleep(10);
3456                 /* never returns */
3457             }
3458         }
3459
3460         s_closed = 0;
3461         ret = at_open(fd, onUnsolicited);
3462
3463         if (ret < 0) {
3464             RLOGE ("AT error %d on at_open\n", ret);
3465             return 0;
3466         }
3467
3468         RIL_requestTimedCallback(initializeCallback, NULL, &TIMEVAL_0);
3469
3470         // Give initializeCallback a chance to dispatched, since
3471         // we don't presently have a cancellation mechanism
3472         sleep(1);
3473
3474         waitForClose();
3475         RLOGI("Re-opening after close");
3476     }
3477 }
3478
3479 #ifdef RIL_SHLIB
3480
3481 pthread_t s_tid_mainloop;
3482
3483 const RIL_RadioFunctions *RIL_Init(const struct RIL_Env *env, int argc, char **argv)
3484 {
3485     int ret;
3486     int fd = -1;
3487     int opt;
3488     pthread_attr_t attr;
3489
3490     s_rilenv = env;
3491
3492     while ( -1 != (opt = getopt(argc, argv, "p:d:s:c:"))) {
3493         switch (opt) {
3494             case 'p':
3495                 s_port = atoi(optarg);
3496                 if (s_port == 0) {
3497                     usage(argv[0]);
3498                     return NULL;
3499                 }
3500                 RLOGI("Opening loopback port %d\n", s_port);
3501             break;
3502
3503             case 'd':
3504                 s_device_path = optarg;
3505                 RLOGI("Opening tty device %s\n", s_device_path);
3506             break;
3507
3508             case 's':
3509                 s_device_path   = optarg;
3510                 s_device_socket = 1;
3511                 RLOGI("Opening socket %s\n", s_device_path);
3512             break;
3513
3514             case 'c':
3515                 RLOGI("Client id received %s\n", optarg);
3516             break;
3517
3518             default:
3519                 usage(argv[0]);
3520                 return NULL;
3521         }
3522     }
3523
3524     if (s_port < 0 && s_device_path == NULL && !isInEmulator()) {
3525         usage(argv[0]);
3526         return NULL;
3527     }
3528
3529     sMdmInfo = calloc(1, sizeof(ModemInfo));
3530     if (!sMdmInfo) {
3531         RLOGE("Unable to alloc memory for ModemInfo");
3532         return NULL;
3533     }
3534     pthread_attr_init (&attr);
3535     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3536     ret = pthread_create(&s_tid_mainloop, &attr, mainLoop, NULL);
3537
3538     return &s_callbacks;
3539 }
3540 #else /* RIL_SHLIB */
3541 int main (int argc, char **argv)
3542 {
3543     int ret;
3544     int fd = -1;
3545     int opt;
3546
3547     while ( -1 != (opt = getopt(argc, argv, "p:d:"))) {
3548         switch (opt) {
3549             case 'p':
3550                 s_port = atoi(optarg);
3551                 if (s_port == 0) {
3552                     usage(argv[0]);
3553                 }
3554                 RLOGI("Opening loopback port %d\n", s_port);
3555             break;
3556
3557             case 'd':
3558                 s_device_path = optarg;
3559                 RLOGI("Opening tty device %s\n", s_device_path);
3560             break;
3561
3562             case 's':
3563                 s_device_path   = optarg;
3564                 s_device_socket = 1;
3565                 RLOGI("Opening socket %s\n", s_device_path);
3566             break;
3567
3568             default:
3569                 usage(argv[0]);
3570         }
3571     }
3572
3573     if (s_port < 0 && s_device_path == NULL && !isInEmulator()) {
3574         usage(argv[0]);
3575     }
3576
3577     RIL_register(&s_callbacks);
3578
3579     mainLoop(NULL);
3580
3581     return 0;
3582 }
3583
3584 #endif /* RIL_SHLIB */