OSDN Git Service

Merge "Fix VTS HAL Radio tests"
[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 <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.15 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 #ifdef WORKAROUND_ERRONEOUS_ANSWER
806 error:
807     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
808     at_response_free(p_response);
809 #endif
810 }
811
812 static void requestDial(void *data, size_t datalen __unused, RIL_Token t)
813 {
814     RIL_Dial *p_dial;
815     char *cmd;
816     const char *clir;
817     int ret;
818
819     p_dial = (RIL_Dial *)data;
820
821     switch (p_dial->clir) {
822         case 1: clir = "I"; break;  /*invocation*/
823         case 2: clir = "i"; break;  /*suppression*/
824         default:
825         case 0: clir = ""; break;   /*subscription default*/
826     }
827
828     asprintf(&cmd, "ATD%s%s;", p_dial->address, clir);
829
830     ret = at_send_command(cmd, NULL);
831
832     free(cmd);
833
834     /* success or failure is ignored by the upper layer here.
835        it will call GET_CURRENT_CALLS and determine success that way */
836     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
837 }
838
839 static void requestWriteSmsToSim(void *data, size_t datalen __unused, RIL_Token t)
840 {
841     RIL_SMS_WriteArgs *p_args;
842     char *cmd;
843     int length;
844     int err;
845     ATResponse *p_response = NULL;
846
847     p_args = (RIL_SMS_WriteArgs *)data;
848
849     length = strlen(p_args->pdu)/2;
850     asprintf(&cmd, "AT+CMGW=%d,%d", length, p_args->status);
851
852     err = at_send_command_sms(cmd, p_args->pdu, "+CMGW:", &p_response);
853
854     if (err != 0 || p_response->success == 0) goto error;
855
856     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
857     at_response_free(p_response);
858
859     return;
860 error:
861     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
862     at_response_free(p_response);
863 }
864
865 static void requestHangup(void *data, size_t datalen __unused, RIL_Token t)
866 {
867     int *p_line;
868
869     int ret;
870     char *cmd;
871
872     p_line = (int *)data;
873
874     // 3GPP 22.030 6.5.5
875     // "Releases a specific active call X"
876     asprintf(&cmd, "AT+CHLD=1%d", p_line[0]);
877
878     ret = at_send_command(cmd, NULL);
879
880     free(cmd);
881
882     /* success or failure is ignored by the upper layer here.
883        it will call GET_CURRENT_CALLS and determine success that way */
884     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
885 }
886
887 static void requestSignalStrength(void *data __unused, size_t datalen __unused, RIL_Token t)
888 {
889     ATResponse *p_response = NULL;
890     int err;
891     char *line;
892     int count = 0;
893     // Accept a response that is at least v6, and up to v10
894     int minNumOfElements=sizeof(RIL_SignalStrength_v6)/sizeof(int);
895     int maxNumOfElements=sizeof(RIL_SignalStrength_v10)/sizeof(int);
896     int response[maxNumOfElements];
897
898     memset(response, 0, sizeof(response));
899
900     err = at_send_command_singleline("AT+CSQ", "+CSQ:", &p_response);
901
902     if (err < 0 || p_response->success == 0) {
903         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
904         goto error;
905     }
906
907     line = p_response->p_intermediates->line;
908
909     err = at_tok_start(&line);
910     if (err < 0) goto error;
911
912     for (count = 0; count < maxNumOfElements; count++) {
913         err = at_tok_nextint(&line, &(response[count]));
914         if (err < 0 && count < minNumOfElements) goto error;
915     }
916
917     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
918
919     at_response_free(p_response);
920     return;
921
922 error:
923     RLOGE("requestSignalStrength must never return an error when radio is on");
924     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
925     at_response_free(p_response);
926 }
927
928 /**
929  * networkModePossible. Decides whether the network mode is appropriate for the
930  * specified modem
931  */
932 static int networkModePossible(ModemInfo *mdm, int nm)
933 {
934     if ((net2modem[nm] & mdm->supportedTechs) == net2modem[nm]) {
935        return 1;
936     }
937     return 0;
938 }
939 static void requestSetPreferredNetworkType( int request __unused, void *data,
940                                             size_t datalen __unused, RIL_Token t )
941 {
942     ATResponse *p_response = NULL;
943     char *cmd = NULL;
944     int value = *(int *)data;
945     int current, old;
946     int err;
947     int32_t preferred = net2pmask[value];
948
949     RLOGD("requestSetPreferredNetworkType: current: %x. New: %x", PREFERRED_NETWORK(sMdmInfo), preferred);
950     if (!networkModePossible(sMdmInfo, value)) {
951         RIL_onRequestComplete(t, RIL_E_MODE_NOT_SUPPORTED, NULL, 0);
952         return;
953     }
954     if (query_ctec(sMdmInfo, &current, NULL) < 0) {
955         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
956         return;
957     }
958     old = PREFERRED_NETWORK(sMdmInfo);
959     RLOGD("old != preferred: %d", old != preferred);
960     if (old != preferred) {
961         asprintf(&cmd, "AT+CTEC=%d,\"%x\"", current, preferred);
962         RLOGD("Sending command: <%s>", cmd);
963         err = at_send_command_singleline(cmd, "+CTEC:", &p_response);
964         free(cmd);
965         if (err || !p_response->success) {
966             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
967             return;
968         }
969         PREFERRED_NETWORK(sMdmInfo) = value;
970         if (!strstr( p_response->p_intermediates->line, "DONE") ) {
971             int current;
972             int res = parse_technology_response(p_response->p_intermediates->line, &current, NULL);
973             switch (res) {
974                 case -1: // Error or unable to parse
975                     break;
976                 case 1: // Only able to parse current
977                 case 0: // Both current and preferred were parsed
978                     setRadioTechnology(sMdmInfo, current);
979                     break;
980             }
981         }
982     }
983     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
984 }
985
986 static void requestGetPreferredNetworkType(int request __unused, void *data __unused,
987                                    size_t datalen __unused, RIL_Token t)
988 {
989     int preferred;
990     unsigned i;
991
992     switch ( query_ctec(sMdmInfo, NULL, &preferred) ) {
993         case -1: // Error or unable to parse
994         case 1: // Only able to parse current
995             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
996             break;
997         case 0: // Both current and preferred were parsed
998             for ( i = 0 ; i < sizeof(net2pmask) / sizeof(int32_t) ; i++ ) {
999                 if (preferred == net2pmask[i]) {
1000                     RIL_onRequestComplete(t, RIL_E_SUCCESS, &i, sizeof(int));
1001                     return;
1002                 }
1003             }
1004             RLOGE("Unknown preferred mode received from modem: %d", preferred);
1005             RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1006             break;
1007     }
1008
1009 }
1010
1011 static void requestCdmaPrlVersion(int request __unused, void *data __unused,
1012                                    size_t datalen __unused, RIL_Token t)
1013 {
1014     int err;
1015     char * responseStr;
1016     ATResponse *p_response = NULL;
1017     const char *cmd;
1018     char *line;
1019
1020     err = at_send_command_singleline("AT+WPRL?", "+WPRL:", &p_response);
1021     if (err < 0 || !p_response->success) goto error;
1022     line = p_response->p_intermediates->line;
1023     err = at_tok_start(&line);
1024     if (err < 0) goto error;
1025     err = at_tok_nextstr(&line, &responseStr);
1026     if (err < 0 || !responseStr) goto error;
1027     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, strlen(responseStr));
1028     at_response_free(p_response);
1029     return;
1030 error:
1031     at_response_free(p_response);
1032     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1033 }
1034
1035 static void requestCdmaBaseBandVersion(int request __unused, void *data __unused,
1036                                    size_t datalen __unused, RIL_Token t)
1037 {
1038     int err;
1039     char * responseStr;
1040     ATResponse *p_response = NULL;
1041     const char *cmd;
1042     const char *prefix;
1043     char *line, *p;
1044     int commas;
1045     int skip;
1046     int count = 4;
1047
1048     // Fixed values. TODO: query modem
1049     responseStr = strdup("1.0.0.0");
1050     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, sizeof(responseStr));
1051     free(responseStr);
1052 }
1053
1054 static void requestCdmaDeviceIdentity(int request __unused, void *data __unused,
1055                                         size_t datalen __unused, RIL_Token t)
1056 {
1057     int err;
1058     int response[4];
1059     char * responseStr[4];
1060     ATResponse *p_response = NULL;
1061     const char *cmd;
1062     const char *prefix;
1063     char *line, *p;
1064     int commas;
1065     int skip;
1066     int count = 4;
1067
1068     // Fixed values. TODO: Query modem
1069     responseStr[0] = "----";
1070     responseStr[1] = "----";
1071     responseStr[2] = "77777777";
1072
1073     err = at_send_command_numeric("AT+CGSN", &p_response);
1074     if (err < 0 || p_response->success == 0) {
1075         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1076         return;
1077     } else {
1078         responseStr[3] = p_response->p_intermediates->line;
1079     }
1080
1081     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, count*sizeof(char*));
1082     at_response_free(p_response);
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
1173 static void requestCdmaGetRoamingPreference(int request __unused, void *data __unused,
1174                                                  size_t datalen __unused, RIL_Token t)
1175 {
1176     int roaming_pref = -1;
1177     ATResponse *p_response = NULL;
1178     char *line;
1179     int res;
1180
1181     res = at_send_command_singleline("AT+WRMP?", "+WRMP:", &p_response);
1182     if (res < 0 || !p_response->success) {
1183         goto error;
1184     }
1185     line = p_response->p_intermediates->line;
1186
1187     res = at_tok_start(&line);
1188     if (res < 0) goto error;
1189
1190     res = at_tok_nextint(&line, &roaming_pref);
1191     if (res < 0) goto error;
1192
1193      RIL_onRequestComplete(t, RIL_E_SUCCESS, &roaming_pref, sizeof(roaming_pref));
1194     return;
1195 error:
1196     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1197 }
1198
1199 static void requestCdmaSetRoamingPreference(int request __unused, void *data,
1200                                                  size_t datalen __unused, RIL_Token t)
1201 {
1202     int *pref = (int *)data;
1203     ATResponse *p_response = NULL;
1204     char *line;
1205     int res;
1206     char *cmd = NULL;
1207
1208     asprintf(&cmd, "AT+WRMP=%d", *pref);
1209     if (cmd == NULL) goto error;
1210
1211     res = at_send_command(cmd, &p_response);
1212     if (res < 0 || !p_response->success)
1213         goto error;
1214
1215     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1216     free(cmd);
1217     return;
1218 error:
1219     free(cmd);
1220     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1221 }
1222
1223 static int parseRegistrationState(char *str, int *type, int *items, int **response)
1224 {
1225     int err;
1226     char *line = str, *p;
1227     int *resp = NULL;
1228     int skip;
1229     int count = 3;
1230     int commas;
1231
1232     RLOGD("parseRegistrationState. Parsing: %s",str);
1233     err = at_tok_start(&line);
1234     if (err < 0) goto error;
1235
1236     /* Ok you have to be careful here
1237      * The solicited version of the CREG response is
1238      * +CREG: n, stat, [lac, cid]
1239      * and the unsolicited version is
1240      * +CREG: stat, [lac, cid]
1241      * The <n> parameter is basically "is unsolicited creg on?"
1242      * which it should always be
1243      *
1244      * Now we should normally get the solicited version here,
1245      * but the unsolicited version could have snuck in
1246      * so we have to handle both
1247      *
1248      * Also since the LAC and CID are only reported when registered,
1249      * we can have 1, 2, 3, or 4 arguments here
1250      *
1251      * finally, a +CGREG: answer may have a fifth value that corresponds
1252      * to the network type, as in;
1253      *
1254      *   +CGREG: n, stat [,lac, cid [,networkType]]
1255      */
1256
1257     /* count number of commas */
1258     commas = 0;
1259     for (p = line ; *p != '\0' ;p++) {
1260         if (*p == ',') commas++;
1261     }
1262
1263     resp = (int *)calloc(commas + 1, sizeof(int));
1264     if (!resp) goto error;
1265     switch (commas) {
1266         case 0: /* +CREG: <stat> */
1267             err = at_tok_nextint(&line, &resp[0]);
1268             if (err < 0) goto error;
1269             resp[1] = -1;
1270             resp[2] = -1;
1271         break;
1272
1273         case 1: /* +CREG: <n>, <stat> */
1274             err = at_tok_nextint(&line, &skip);
1275             if (err < 0) goto error;
1276             err = at_tok_nextint(&line, &resp[0]);
1277             if (err < 0) goto error;
1278             resp[1] = -1;
1279             resp[2] = -1;
1280             if (err < 0) goto error;
1281         break;
1282
1283         case 2: /* +CREG: <stat>, <lac>, <cid> */
1284             err = at_tok_nextint(&line, &resp[0]);
1285             if (err < 0) goto error;
1286             err = at_tok_nexthexint(&line, &resp[1]);
1287             if (err < 0) goto error;
1288             err = at_tok_nexthexint(&line, &resp[2]);
1289             if (err < 0) goto error;
1290         break;
1291         case 3: /* +CREG: <n>, <stat>, <lac>, <cid> */
1292             err = at_tok_nextint(&line, &skip);
1293             if (err < 0) goto error;
1294             err = at_tok_nextint(&line, &resp[0]);
1295             if (err < 0) goto error;
1296             err = at_tok_nexthexint(&line, &resp[1]);
1297             if (err < 0) goto error;
1298             err = at_tok_nexthexint(&line, &resp[2]);
1299             if (err < 0) goto error;
1300         break;
1301         /* special case for CGREG, there is a fourth parameter
1302          * that is the network type (unknown/gprs/edge/umts)
1303          */
1304         case 4: /* +CGREG: <n>, <stat>, <lac>, <cid>, <networkType> */
1305             err = at_tok_nextint(&line, &skip);
1306             if (err < 0) goto error;
1307             err = at_tok_nextint(&line, &resp[0]);
1308             if (err < 0) goto error;
1309             err = at_tok_nexthexint(&line, &resp[1]);
1310             if (err < 0) goto error;
1311             err = at_tok_nexthexint(&line, &resp[2]);
1312             if (err < 0) goto error;
1313             err = at_tok_nexthexint(&line, &resp[3]);
1314             if (err < 0) goto error;
1315             count = 4;
1316         break;
1317         default:
1318             goto error;
1319     }
1320     s_lac = resp[1];
1321     s_cid = resp[2];
1322     if (response)
1323         *response = resp;
1324     if (items)
1325         *items = commas + 1;
1326     if (type)
1327         *type = techFromModemType(TECH(sMdmInfo));
1328     return 0;
1329 error:
1330     free(resp);
1331     return -1;
1332 }
1333
1334 #define REG_STATE_LEN 15
1335 #define REG_DATA_STATE_LEN 6
1336 static void requestRegistrationState(int request, void *data __unused,
1337                                         size_t datalen __unused, RIL_Token t)
1338 {
1339     int err;
1340     int *registration;
1341     char **responseStr = NULL;
1342     ATResponse *p_response = NULL;
1343     const char *cmd;
1344     const char *prefix;
1345     char *line;
1346     int i = 0, j, numElements = 0;
1347     int count = 3;
1348     int type, startfrom;
1349
1350     RLOGD("requestRegistrationState");
1351     if (request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
1352         cmd = "AT+CREG?";
1353         prefix = "+CREG:";
1354         numElements = REG_STATE_LEN;
1355     } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1356         cmd = "AT+CGREG?";
1357         prefix = "+CGREG:";
1358         numElements = REG_DATA_STATE_LEN;
1359     } else {
1360         assert(0);
1361         goto error;
1362     }
1363
1364     err = at_send_command_singleline(cmd, prefix, &p_response);
1365
1366     if (err != 0) goto error;
1367
1368     line = p_response->p_intermediates->line;
1369
1370     if (parseRegistrationState(line, &type, &count, &registration)) goto error;
1371
1372     responseStr = malloc(numElements * sizeof(char *));
1373     if (!responseStr) goto error;
1374     memset(responseStr, 0, numElements * sizeof(char *));
1375     /**
1376      * The first '4' bytes for both registration states remain the same.
1377      * But if the request is 'DATA_REGISTRATION_STATE',
1378      * the 5th and 6th byte(s) are optional.
1379      */
1380     if (is3gpp2(type) == 1) {
1381         RLOGD("registration state type: 3GPP2");
1382         // TODO: Query modem
1383         startfrom = 3;
1384         if(request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
1385             asprintf(&responseStr[3], "8");     // EvDo revA
1386             asprintf(&responseStr[4], "1");     // BSID
1387             asprintf(&responseStr[5], "123");   // Latitude
1388             asprintf(&responseStr[6], "222");   // Longitude
1389             asprintf(&responseStr[7], "0");     // CSS Indicator
1390             asprintf(&responseStr[8], "4");     // SID
1391             asprintf(&responseStr[9], "65535"); // NID
1392             asprintf(&responseStr[10], "0");    // Roaming indicator
1393             asprintf(&responseStr[11], "1");    // System is in PRL
1394             asprintf(&responseStr[12], "0");    // Default Roaming indicator
1395             asprintf(&responseStr[13], "0");    // Reason for denial
1396             asprintf(&responseStr[14], "0");    // Primary Scrambling Code of Current cell
1397       } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1398             asprintf(&responseStr[3], "8");   // Available data radio technology
1399       }
1400     } else { // type == RADIO_TECH_3GPP
1401         RLOGD("registration state type: 3GPP");
1402         startfrom = 0;
1403         asprintf(&responseStr[1], "%x", registration[1]);
1404         asprintf(&responseStr[2], "%x", registration[2]);
1405         if (count > 3)
1406             asprintf(&responseStr[3], "%d", registration[3]);
1407     }
1408     asprintf(&responseStr[0], "%d", registration[0]);
1409
1410     /**
1411      * Optional bytes for DATA_REGISTRATION_STATE request
1412      * 4th byte : Registration denial code
1413      * 5th byte : The max. number of simultaneous Data Calls
1414      */
1415     if(request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
1416         // asprintf(&responseStr[4], "3");
1417         // asprintf(&responseStr[5], "1");
1418     }
1419
1420     for (j = startfrom; j < numElements; j++) {
1421         if (!responseStr[i]) goto error;
1422     }
1423     free(registration);
1424     registration = NULL;
1425
1426     RIL_onRequestComplete(t, RIL_E_SUCCESS, responseStr, numElements*sizeof(responseStr));
1427     for (j = 0; j < numElements; j++ ) {
1428         free(responseStr[j]);
1429         responseStr[j] = NULL;
1430     }
1431     free(responseStr);
1432     responseStr = NULL;
1433     at_response_free(p_response);
1434
1435     return;
1436 error:
1437     if (responseStr) {
1438         for (j = 0; j < numElements; j++) {
1439             free(responseStr[j]);
1440             responseStr[j] = NULL;
1441         }
1442         free(responseStr);
1443         responseStr = NULL;
1444     }
1445     RLOGE("requestRegistrationState must never return an error when radio is on");
1446     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1447     at_response_free(p_response);
1448 }
1449
1450 static void requestOperator(void *data __unused, size_t datalen __unused, RIL_Token t)
1451 {
1452     int err;
1453     int i;
1454     int skip;
1455     ATLine *p_cur;
1456     char *response[3];
1457
1458     memset(response, 0, sizeof(response));
1459
1460     ATResponse *p_response = NULL;
1461
1462     err = at_send_command_multiline(
1463         "AT+COPS=3,0;+COPS?;+COPS=3,1;+COPS?;+COPS=3,2;+COPS?",
1464         "+COPS:", &p_response);
1465
1466     /* we expect 3 lines here:
1467      * +COPS: 0,0,"T - Mobile"
1468      * +COPS: 0,1,"TMO"
1469      * +COPS: 0,2,"310170"
1470      */
1471
1472     if (err != 0) goto error;
1473
1474     for (i = 0, p_cur = p_response->p_intermediates
1475             ; p_cur != NULL
1476             ; p_cur = p_cur->p_next, i++
1477     ) {
1478         char *line = p_cur->line;
1479
1480         err = at_tok_start(&line);
1481         if (err < 0) goto error;
1482
1483         err = at_tok_nextint(&line, &skip);
1484         if (err < 0) goto error;
1485
1486         // If we're unregistered, we may just get
1487         // a "+COPS: 0" response
1488         if (!at_tok_hasmore(&line)) {
1489             response[i] = NULL;
1490             continue;
1491         }
1492
1493         err = at_tok_nextint(&line, &skip);
1494         if (err < 0) goto error;
1495
1496         // a "+COPS: 0, n" response is also possible
1497         if (!at_tok_hasmore(&line)) {
1498             response[i] = NULL;
1499             continue;
1500         }
1501
1502         err = at_tok_nextstr(&line, &(response[i]));
1503         if (err < 0) goto error;
1504         // Simple assumption that mcc and mnc are 3 digits each
1505         if (strlen(response[i]) == 6) {
1506             if (sscanf(response[i], "%3d%3d", &s_mcc, &s_mnc) != 2) {
1507                 RLOGE("requestOperator expected mccmnc to be 6 decimal digits");
1508             }
1509         }
1510     }
1511
1512     if (i != 3) {
1513         /* expect 3 lines exactly */
1514         goto error;
1515     }
1516
1517     RIL_onRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
1518     at_response_free(p_response);
1519
1520     return;
1521 error:
1522     RLOGE("requestOperator must not return error when radio is on");
1523     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1524     at_response_free(p_response);
1525 }
1526
1527 static void requestCdmaSendSMS(void *data, size_t datalen, RIL_Token t)
1528 {
1529     int err = 1; // Set to go to error:
1530     RIL_SMS_Response response;
1531     RIL_CDMA_SMS_Message* rcsm;
1532
1533     RLOGD("requestCdmaSendSMS datalen=%zu, sizeof(RIL_CDMA_SMS_Message)=%zu",
1534             datalen, sizeof(RIL_CDMA_SMS_Message));
1535
1536     // verify data content to test marshalling/unmarshalling:
1537     rcsm = (RIL_CDMA_SMS_Message*)data;
1538     RLOGD("TeleserviceID=%d, bIsServicePresent=%d, \
1539             uServicecategory=%d, sAddress.digit_mode=%d, \
1540             sAddress.Number_mode=%d, sAddress.number_type=%d, ",
1541             rcsm->uTeleserviceID,  rcsm->bIsServicePresent,
1542             rcsm->uServicecategory,rcsm->sAddress.digit_mode,
1543             rcsm->sAddress.number_mode,rcsm->sAddress.number_type);
1544
1545     if (err != 0) goto error;
1546
1547     // Cdma Send SMS implementation will go here:
1548     // But it is not implemented yet.
1549
1550     memset(&response, 0, sizeof(response));
1551     response.messageRef = 1;
1552     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
1553     return;
1554
1555 error:
1556     // Cdma Send SMS will always cause send retry error.
1557     response.messageRef = -1;
1558     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
1559 }
1560
1561 static void requestSendSMS(void *data, size_t datalen, RIL_Token t)
1562 {
1563     int err;
1564     const char *smsc;
1565     const char *pdu;
1566     int tpLayerLength;
1567     char *cmd1, *cmd2;
1568     RIL_SMS_Response response;
1569     ATResponse *p_response = NULL;
1570
1571     memset(&response, 0, sizeof(response));
1572     RLOGD("requestSendSMS datalen =%zu", datalen);
1573
1574     if (s_ims_gsm_fail != 0) goto error;
1575     if (s_ims_gsm_retry != 0) goto error2;
1576
1577     smsc = ((const char **)data)[0];
1578     pdu = ((const char **)data)[1];
1579
1580     tpLayerLength = strlen(pdu)/2;
1581
1582     // "NULL for default SMSC"
1583     if (smsc == NULL) {
1584         smsc= "00";
1585     }
1586
1587     asprintf(&cmd1, "AT+CMGS=%d", tpLayerLength);
1588     asprintf(&cmd2, "%s%s", smsc, pdu);
1589
1590     err = at_send_command_sms(cmd1, cmd2, "+CMGS:", &p_response);
1591
1592     free(cmd1);
1593     free(cmd2);
1594
1595     if (err != 0 || p_response->success == 0) goto error;
1596
1597     /* FIXME fill in messageRef and ackPDU */
1598     response.messageRef = 1;
1599     RIL_onRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
1600     at_response_free(p_response);
1601
1602     return;
1603 error:
1604     response.messageRef = -2;
1605     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, &response, sizeof(response));
1606     at_response_free(p_response);
1607     return;
1608 error2:
1609     // send retry error.
1610     response.messageRef = -1;
1611     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
1612     at_response_free(p_response);
1613     return;
1614     }
1615
1616 static void requestImsSendSMS(void *data, size_t datalen, RIL_Token t)
1617 {
1618     RIL_IMS_SMS_Message *p_args;
1619     RIL_SMS_Response response;
1620
1621     memset(&response, 0, sizeof(response));
1622
1623     RLOGD("requestImsSendSMS: datalen=%zu, "
1624         "registered=%d, service=%d, format=%d, ims_perm_fail=%d, "
1625         "ims_retry=%d, gsm_fail=%d, gsm_retry=%d",
1626         datalen, s_ims_registered, s_ims_services, s_ims_format,
1627         s_ims_cause_perm_failure, s_ims_cause_retry, s_ims_gsm_fail,
1628         s_ims_gsm_retry);
1629
1630     // figure out if this is gsm/cdma format
1631     // then route it to requestSendSMS vs requestCdmaSendSMS respectively
1632     p_args = (RIL_IMS_SMS_Message *)data;
1633
1634     if (0 != s_ims_cause_perm_failure ) goto error;
1635
1636     // want to fail over ims and this is first request over ims
1637     if (0 != s_ims_cause_retry && 0 == p_args->retry) goto error2;
1638
1639     if (RADIO_TECH_3GPP == p_args->tech) {
1640         return requestSendSMS(p_args->message.gsmMessage,
1641                 datalen - sizeof(RIL_RadioTechnologyFamily),
1642                 t);
1643     } else if (RADIO_TECH_3GPP2 == p_args->tech) {
1644         return requestCdmaSendSMS(p_args->message.cdmaMessage,
1645                 datalen - sizeof(RIL_RadioTechnologyFamily),
1646                 t);
1647     } else {
1648         RLOGE("requestImsSendSMS invalid format value =%d", p_args->tech);
1649     }
1650
1651 error:
1652     response.messageRef = -2;
1653     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, &response, sizeof(response));
1654     return;
1655
1656 error2:
1657     response.messageRef = -1;
1658     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
1659 }
1660
1661 static void requestSimOpenChannel(void *data, size_t datalen, RIL_Token t)
1662 {
1663     ATResponse *p_response = NULL;
1664     int32_t session_id;
1665     int err;
1666     char cmd[32];
1667     char dummy;
1668     char *line;
1669
1670     // Max length is 16 bytes according to 3GPP spec 27.007 section 8.45
1671     if (data == NULL || datalen == 0 || datalen > 16) {
1672         ALOGE("Invalid data passed to requestSimOpenChannel");
1673         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1674         return;
1675     }
1676
1677     snprintf(cmd, sizeof(cmd), "AT+CCHO=%s", data);
1678
1679     err = at_send_command_numeric(cmd, &p_response);
1680     if (err < 0 || p_response == NULL || p_response->success == 0) {
1681         ALOGE("Error %d opening logical channel: %d",
1682               err, p_response ? p_response->success : 0);
1683         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1684         at_response_free(p_response);
1685         return;
1686     }
1687
1688     // Ensure integer only by scanning for an extra char but expect one result
1689     line = p_response->p_intermediates->line;
1690     if (sscanf(line, "%" SCNd32 "%c", &session_id, &dummy) != 1) {
1691         ALOGE("Invalid AT response, expected integer, was '%s'", line);
1692         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1693         return;
1694     }
1695
1696     RIL_onRequestComplete(t, RIL_E_SUCCESS, &session_id, sizeof(&session_id));
1697     at_response_free(p_response);
1698 }
1699
1700 static void requestSimCloseChannel(void *data, size_t datalen, RIL_Token t)
1701 {
1702     ATResponse *p_response = NULL;
1703     int32_t session_id;
1704     int err;
1705     char cmd[32];
1706
1707     if (data == NULL || datalen != sizeof(session_id)) {
1708         ALOGE("Invalid data passed to requestSimCloseChannel");
1709         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1710         return;
1711     }
1712     session_id = ((int32_t *)data)[0];
1713     snprintf(cmd, sizeof(cmd), "AT+CCHC=%" PRId32, session_id);
1714     err = at_send_command_singleline(cmd, "+CCHC", &p_response);
1715
1716     if (err < 0 || p_response == NULL || p_response->success == 0) {
1717         ALOGE("Error %d closing logical channel %d: %d",
1718               err, session_id, p_response ? p_response->success : 0);
1719         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1720         at_response_free(p_response);
1721         return;
1722     }
1723
1724     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1725
1726     at_response_free(p_response);
1727 }
1728
1729 static void requestSimTransmitApduChannel(void *data,
1730                                           size_t datalen,
1731                                           RIL_Token t)
1732 {
1733     ATResponse *p_response = NULL;
1734     int err;
1735     char *cmd;
1736     char *line;
1737     size_t cmd_size;
1738     RIL_SIM_IO_Response sim_response;
1739     RIL_SIM_APDU *apdu = (RIL_SIM_APDU *)data;
1740
1741     if (apdu == NULL || datalen != sizeof(RIL_SIM_APDU)) {
1742         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1743         return;
1744     }
1745
1746     cmd_size = 10 + (apdu->data ? strlen(apdu->data) : 0);
1747     asprintf(&cmd, "AT+CGLA=%d,%zu,%02x%02x%02x%02x%02x%s",
1748              apdu->sessionid, cmd_size, apdu->cla, apdu->instruction,
1749              apdu->p1, apdu->p2, apdu->p3, apdu->data ? apdu->data : "");
1750
1751     err = at_send_command_singleline(cmd, "+CGLA", &p_response);
1752     free(cmd);
1753     if (err < 0 || p_response == NULL || p_response->success == 0) {
1754         ALOGE("Error %d transmitting APDU: %d",
1755               err, p_response ? p_response->success : 0);
1756         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1757         at_response_free(p_response);
1758         return;
1759     }
1760
1761     line = p_response->p_intermediates->line;
1762     err = parseSimResponseLine(line, &sim_response);
1763
1764     if (err == 0) {
1765         RIL_onRequestComplete(t, RIL_E_SUCCESS,
1766                               &sim_response, sizeof(sim_response));
1767     } else {
1768         ALOGE("Error %d parsing SIM response line: %s", err, line);
1769         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1770     }
1771     at_response_free(p_response);
1772 }
1773
1774 static void requestSetupDataCall(void *data, size_t datalen, RIL_Token t)
1775 {
1776     const char *apn;
1777     char *cmd;
1778     int err;
1779     ATResponse *p_response = NULL;
1780
1781     apn = ((const char **)data)[2];
1782
1783 #ifdef USE_TI_COMMANDS
1784     // Config for multislot class 10 (probably default anyway eh?)
1785     err = at_send_command("AT%CPRIM=\"GMM\",\"CONFIG MULTISLOT_CLASS=<10>\"",
1786                         NULL);
1787
1788     err = at_send_command("AT%DATA=2,\"UART\",1,,\"SER\",\"UART\",0", NULL);
1789 #endif /* USE_TI_COMMANDS */
1790
1791     int fd, qmistatus;
1792     size_t cur = 0;
1793     size_t len;
1794     ssize_t written, rlen;
1795     char status[32] = {0};
1796     int retry = 10;
1797     const char *pdp_type;
1798
1799     RLOGD("requesting data connection to APN '%s'", apn);
1800
1801     fd = open ("/dev/qmi", O_RDWR);
1802     if (fd >= 0) { /* the device doesn't exist on the emulator */
1803
1804         RLOGD("opened the qmi device\n");
1805         asprintf(&cmd, "up:%s", apn);
1806         len = strlen(cmd);
1807
1808         while (cur < len) {
1809             do {
1810                 written = write (fd, cmd + cur, len - cur);
1811             } while (written < 0 && errno == EINTR);
1812
1813             if (written < 0) {
1814                 RLOGE("### ERROR writing to /dev/qmi");
1815                 close(fd);
1816                 goto error;
1817             }
1818
1819             cur += written;
1820         }
1821
1822         // wait for interface to come online
1823
1824         do {
1825             sleep(1);
1826             do {
1827                 rlen = read(fd, status, 31);
1828             } while (rlen < 0 && errno == EINTR);
1829
1830             if (rlen < 0) {
1831                 RLOGE("### ERROR reading from /dev/qmi");
1832                 close(fd);
1833                 goto error;
1834             } else {
1835                 status[rlen] = '\0';
1836                 RLOGD("### status: %s", status);
1837             }
1838         } while (strncmp(status, "STATE=up", 8) && strcmp(status, "online") && --retry);
1839
1840         close(fd);
1841
1842         if (retry == 0) {
1843             RLOGE("### Failed to get data connection up\n");
1844             goto error;
1845         }
1846
1847         qmistatus = system("netcfg rmnet0 dhcp");
1848
1849         RLOGD("netcfg rmnet0 dhcp: status %d\n", qmistatus);
1850
1851         if (qmistatus < 0) goto error;
1852
1853     } else {
1854
1855         if (datalen > 6 * sizeof(char *)) {
1856             pdp_type = ((const char **)data)[6];
1857         } else {
1858             pdp_type = "IP";
1859         }
1860
1861         asprintf(&cmd, "AT+CGDCONT=1,\"%s\",\"%s\",,0,0", pdp_type, apn);
1862         //FIXME check for error here
1863         err = at_send_command(cmd, NULL);
1864         free(cmd);
1865
1866         // Set required QoS params to default
1867         err = at_send_command("AT+CGQREQ=1", NULL);
1868
1869         // Set minimum QoS params to default
1870         err = at_send_command("AT+CGQMIN=1", NULL);
1871
1872         // packet-domain event reporting
1873         err = at_send_command("AT+CGEREP=1,0", NULL);
1874
1875         // Hangup anything that's happening there now
1876         err = at_send_command("AT+CGACT=1,0", NULL);
1877
1878         // Start data on PDP context 1
1879         err = at_send_command("ATD*99***1#", &p_response);
1880
1881         if (err < 0 || p_response->success == 0) {
1882             goto error;
1883         }
1884     }
1885
1886     requestOrSendDataCallList(&t);
1887
1888     at_response_free(p_response);
1889
1890     return;
1891 error:
1892     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1893     at_response_free(p_response);
1894
1895 }
1896
1897 static void requestSMSAcknowledge(void *data, size_t datalen __unused, RIL_Token t)
1898 {
1899     int ackSuccess;
1900     int err;
1901
1902     ackSuccess = ((int *)data)[0];
1903
1904     if (ackSuccess == 1) {
1905         err = at_send_command("AT+CNMA=1", NULL);
1906     } else if (ackSuccess == 0)  {
1907         err = at_send_command("AT+CNMA=2", NULL);
1908     } else {
1909         RLOGE("unsupported arg to RIL_REQUEST_SMS_ACKNOWLEDGE\n");
1910         goto error;
1911     }
1912
1913     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1914 error:
1915     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1916
1917 }
1918
1919 static void  requestSIM_IO(void *data, size_t datalen __unused, RIL_Token t)
1920 {
1921     ATResponse *p_response = NULL;
1922     RIL_SIM_IO_Response sr;
1923     int err;
1924     char *cmd = NULL;
1925     RIL_SIM_IO_v6 *p_args;
1926     char *line;
1927
1928     memset(&sr, 0, sizeof(sr));
1929
1930     p_args = (RIL_SIM_IO_v6 *)data;
1931
1932     /* FIXME handle pin2 */
1933
1934     if (p_args->data == NULL) {
1935         asprintf(&cmd, "AT+CRSM=%d,%d,%d,%d,%d",
1936                     p_args->command, p_args->fileid,
1937                     p_args->p1, p_args->p2, p_args->p3);
1938     } else {
1939         asprintf(&cmd, "AT+CRSM=%d,%d,%d,%d,%d,%s",
1940                     p_args->command, p_args->fileid,
1941                     p_args->p1, p_args->p2, p_args->p3, p_args->data);
1942     }
1943
1944     err = at_send_command_singleline(cmd, "+CRSM:", &p_response);
1945
1946     if (err < 0 || p_response->success == 0) {
1947         goto error;
1948     }
1949
1950     line = p_response->p_intermediates->line;
1951
1952     err = parseSimResponseLine(line, &sr);
1953     if (err < 0) {
1954         goto error;
1955     }
1956
1957     RIL_onRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
1958     at_response_free(p_response);
1959     free(cmd);
1960
1961     return;
1962 error:
1963     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
1964     at_response_free(p_response);
1965     free(cmd);
1966
1967 }
1968
1969 static void  requestEnterSimPin(void*  data, size_t  datalen, RIL_Token  t)
1970 {
1971     ATResponse   *p_response = NULL;
1972     int           err;
1973     char*         cmd = NULL;
1974     const char**  strings = (const char**)data;;
1975
1976     if ( datalen == sizeof(char*) ) {
1977         asprintf(&cmd, "AT+CPIN=%s", strings[0]);
1978     } else if ( datalen == 2*sizeof(char*) ) {
1979         asprintf(&cmd, "AT+CPIN=%s,%s", strings[0], strings[1]);
1980     } else
1981         goto error;
1982
1983     err = at_send_command_singleline(cmd, "+CPIN:", &p_response);
1984     free(cmd);
1985
1986     if (err < 0 || p_response->success == 0) {
1987 error:
1988         RIL_onRequestComplete(t, RIL_E_PASSWORD_INCORRECT, NULL, 0);
1989     } else {
1990         RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
1991     }
1992     at_response_free(p_response);
1993 }
1994
1995
1996 static void  requestSendUSSD(void *data, size_t datalen __unused, RIL_Token t)
1997 {
1998     const char *ussdRequest;
1999
2000     ussdRequest = (char *)(data);
2001
2002
2003     RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
2004
2005 // @@@ TODO
2006
2007 }
2008
2009 static void requestExitEmergencyMode(void *data __unused, size_t datalen __unused, RIL_Token t)
2010 {
2011     int err;
2012     ATResponse *p_response = NULL;
2013
2014     err = at_send_command("AT+WSOS=0", &p_response);
2015
2016     if (err < 0 || p_response->success == 0) {
2017         RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2018         return;
2019     }
2020
2021     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2022 }
2023
2024 // TODO: Use all radio types
2025 static int techFromModemType(int mdmtype)
2026 {
2027     int ret = -1;
2028     switch (1 << mdmtype) {
2029         case MDM_CDMA:
2030             ret = RADIO_TECH_1xRTT;
2031             break;
2032         case MDM_EVDO:
2033             ret = RADIO_TECH_EVDO_A;
2034             break;
2035         case MDM_GSM:
2036             ret = RADIO_TECH_GPRS;
2037             break;
2038         case MDM_WCDMA:
2039             ret = RADIO_TECH_HSPA;
2040             break;
2041         case MDM_LTE:
2042             ret = RADIO_TECH_LTE;
2043             break;
2044     }
2045     return ret;
2046 }
2047
2048 static void requestGetCellInfoList(void *data __unused, size_t datalen __unused, RIL_Token t)
2049 {
2050     uint64_t curTime = ril_nano_time();
2051     RIL_CellInfo ci[1] =
2052     {
2053         { // ci[0]
2054             1, // cellInfoType
2055             1, // registered
2056             RIL_TIMESTAMP_TYPE_MODEM,
2057             curTime - 1000, // Fake some time in the past
2058             { // union CellInfo
2059                 {  // RIL_CellInfoGsm gsm
2060                     {  // gsm.cellIdneityGsm
2061                         s_mcc, // mcc
2062                         s_mnc, // mnc
2063                         s_lac, // lac
2064                         s_cid, // cid
2065                     },
2066                     {  // gsm.signalStrengthGsm
2067                         10, // signalStrength
2068                         0  // bitErrorRate
2069                     }
2070                 }
2071             }
2072         }
2073     };
2074
2075     RIL_onRequestComplete(t, RIL_E_SUCCESS, ci, sizeof(ci));
2076 }
2077
2078
2079 static void requestSetCellInfoListRate(void *data, size_t datalen __unused, RIL_Token t)
2080 {
2081     // For now we'll save the rate but no RIL_UNSOL_CELL_INFO_LIST messages
2082     // will be sent.
2083     assert (datalen == sizeof(int));
2084     s_cell_info_rate_ms = ((int *)data)[0];
2085
2086     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2087 }
2088
2089 static void requestGetHardwareConfig(void *data, size_t datalen, RIL_Token t)
2090 {
2091    // TODO - hook this up with real query/info from radio.
2092
2093    RIL_HardwareConfig hwCfg;
2094
2095    RIL_UNUSED_PARM(data);
2096    RIL_UNUSED_PARM(datalen);
2097
2098    hwCfg.type = -1;
2099
2100    RIL_onRequestComplete(t, RIL_E_SUCCESS, &hwCfg, sizeof(hwCfg));
2101 }
2102
2103 static void requestGetTtyMode(void *data, size_t datalen, RIL_Token t)
2104 {
2105    int  ttyModeResponse;
2106
2107    RIL_UNUSED_PARM(data);
2108    RIL_UNUSED_PARM(datalen);
2109
2110    ttyModeResponse = (getSIMStatus() == SIM_READY) ? 1  // TTY Full
2111                                                    : 0; // TTY Off
2112
2113    RIL_onRequestComplete(t, RIL_E_SUCCESS, &ttyModeResponse, sizeof(ttyModeResponse));
2114 }
2115
2116 static void requestGetRadioCapability(void *data, size_t datalen, RIL_Token t)
2117 {
2118    RIL_RadioCapability radioCapability;
2119
2120    RIL_UNUSED_PARM(data);
2121    RIL_UNUSED_PARM(datalen);
2122
2123    radioCapability.version = RIL_RADIO_CAPABILITY_VERSION;
2124    radioCapability.session = 0;
2125    radioCapability.phase   = 0;
2126    radioCapability.rat     = 0;
2127    radioCapability.logicalModemUuid[0] = '\0';
2128    radioCapability.status  = RC_STATUS_SUCCESS;
2129
2130    RIL_onRequestComplete(t, RIL_E_SUCCESS, &radioCapability, sizeof(radioCapability));
2131 }
2132
2133 static void requestGetMute(void *data, size_t datalen, RIL_Token t)
2134 {
2135    int  muteResponse;
2136
2137    RIL_UNUSED_PARM(data);
2138    RIL_UNUSED_PARM(datalen);
2139
2140    muteResponse = 0; // Mute disabled
2141
2142    RIL_onRequestComplete(t, RIL_E_SUCCESS, &muteResponse, sizeof(muteResponse));
2143 }
2144
2145 /*** Callback methods from the RIL library to us ***/
2146
2147 /**
2148  * Call from RIL to us to make a RIL_REQUEST
2149  *
2150  * Must be completed with a call to RIL_onRequestComplete()
2151  *
2152  * RIL_onRequestComplete() may be called from any thread, before or after
2153  * this function returns.
2154  *
2155  * Because onRequest function could be called from multiple different thread,
2156  * we must ensure that the underlying at_send_command_* function
2157  * is atomic.
2158  */
2159 static void
2160 onRequest (int request, void *data, size_t datalen, RIL_Token t)
2161 {
2162     ATResponse *p_response;
2163     int err;
2164
2165     RLOGD("onRequest: %s", requestToString(request));
2166
2167     /* Ignore all requests except RIL_REQUEST_GET_SIM_STATUS
2168      * when RADIO_STATE_UNAVAILABLE.
2169      */
2170     if (sState == RADIO_STATE_UNAVAILABLE
2171         && request != RIL_REQUEST_GET_SIM_STATUS
2172     ) {
2173         RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
2174         return;
2175     }
2176
2177     /* Ignore all non-power requests when RADIO_STATE_OFF
2178      * (except RIL_REQUEST_GET_SIM_STATUS)
2179      */
2180     if (sState == RADIO_STATE_OFF) {
2181         switch(request) {
2182             case RIL_REQUEST_BASEBAND_VERSION:
2183             case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
2184             case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:
2185             case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:
2186             case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
2187             case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
2188             case RIL_REQUEST_CDMA_SUBSCRIPTION:
2189             case RIL_REQUEST_DEVICE_IDENTITY:
2190             case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
2191             case RIL_REQUEST_GET_ACTIVITY_INFO:
2192             case RIL_REQUEST_GET_CARRIER_RESTRICTIONS:
2193             case RIL_REQUEST_GET_CURRENT_CALLS:
2194             case RIL_REQUEST_GET_IMEI:
2195             case RIL_REQUEST_GET_MUTE:
2196             case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
2197             case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
2198             case RIL_REQUEST_GET_RADIO_CAPABILITY:
2199             case RIL_REQUEST_GET_SIM_STATUS:
2200             case RIL_REQUEST_NV_RESET_CONFIG:
2201             case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE:
2202             case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
2203             case RIL_REQUEST_QUERY_TTY_MODE:
2204             case RIL_REQUEST_RADIO_POWER:
2205             case RIL_REQUEST_SET_BAND_MODE:
2206             case RIL_REQUEST_SET_CARRIER_RESTRICTIONS:
2207             case RIL_REQUEST_SET_LOCATION_UPDATES:
2208             case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
2209             case RIL_REQUEST_SET_TTY_MODE:
2210             case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
2211             case RIL_REQUEST_STOP_LCE:
2212             case RIL_REQUEST_VOICE_RADIO_TECH:
2213                 // Process all the above, even though the radio is off
2214                 break;
2215
2216             default:
2217                 // For all others, say NOT_AVAILABLE because the radio is off
2218                 RIL_onRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
2219                 return;
2220         }
2221     }
2222
2223     switch (request) {
2224         case RIL_REQUEST_GET_SIM_STATUS: {
2225             RIL_CardStatus_v6 *p_card_status;
2226             char *p_buffer;
2227             int buffer_size;
2228
2229             int result = getCardStatus(&p_card_status);
2230             if (result == RIL_E_SUCCESS) {
2231                 p_buffer = (char *)p_card_status;
2232                 buffer_size = sizeof(*p_card_status);
2233             } else {
2234                 p_buffer = NULL;
2235                 buffer_size = 0;
2236             }
2237             RIL_onRequestComplete(t, result, p_buffer, buffer_size);
2238             freeCardStatus(p_card_status);
2239             break;
2240         }
2241         case RIL_REQUEST_GET_CURRENT_CALLS:
2242             requestGetCurrentCalls(data, datalen, t);
2243             break;
2244         case RIL_REQUEST_DIAL:
2245             requestDial(data, datalen, t);
2246             break;
2247         case RIL_REQUEST_HANGUP:
2248             requestHangup(data, datalen, t);
2249             break;
2250         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
2251             // 3GPP 22.030 6.5.5
2252             // "Releases all held calls or sets User Determined User Busy
2253             //  (UDUB) for a waiting call."
2254             at_send_command("AT+CHLD=0", NULL);
2255
2256             /* success or failure is ignored by the upper layer here.
2257                it will call GET_CURRENT_CALLS and determine success that way */
2258             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2259             break;
2260         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
2261             // 3GPP 22.030 6.5.5
2262             // "Releases all active calls (if any exist) and accepts
2263             //  the other (held or waiting) call."
2264             at_send_command("AT+CHLD=1", NULL);
2265
2266             /* success or failure is ignored by the upper layer here.
2267                it will call GET_CURRENT_CALLS and determine success that way */
2268             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2269             break;
2270         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
2271             // 3GPP 22.030 6.5.5
2272             // "Places all active calls (if any exist) on hold and accepts
2273             //  the other (held or waiting) call."
2274             at_send_command("AT+CHLD=2", NULL);
2275
2276 #ifdef WORKAROUND_ERRONEOUS_ANSWER
2277             s_expectAnswer = 1;
2278 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
2279
2280             /* success or failure is ignored by the upper layer here.
2281                it will call GET_CURRENT_CALLS and determine success that way */
2282             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2283             break;
2284         case RIL_REQUEST_ANSWER:
2285             at_send_command("ATA", NULL);
2286
2287 #ifdef WORKAROUND_ERRONEOUS_ANSWER
2288             s_expectAnswer = 1;
2289 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
2290
2291             /* success or failure is ignored by the upper layer here.
2292                it will call GET_CURRENT_CALLS and determine success that way */
2293             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2294             break;
2295         case RIL_REQUEST_CONFERENCE:
2296             // 3GPP 22.030 6.5.5
2297             // "Adds a held call to the conversation"
2298             at_send_command("AT+CHLD=3", NULL);
2299
2300             /* success or failure is ignored by the upper layer here.
2301                it will call GET_CURRENT_CALLS and determine success that way */
2302             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2303             break;
2304         case RIL_REQUEST_UDUB:
2305             /* user determined user busy */
2306             /* sometimes used: ATH */
2307             at_send_command("ATH", NULL);
2308
2309             /* success or failure is ignored by the upper layer here.
2310                it will call GET_CURRENT_CALLS and determine success that way */
2311             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2312             break;
2313
2314         case RIL_REQUEST_SEPARATE_CONNECTION:
2315             {
2316                 char  cmd[12];
2317                 int   party = ((int*)data)[0];
2318
2319                 // Make sure that party is in a valid range.
2320                 // (Note: The Telephony middle layer imposes a range of 1 to 7.
2321                 // It's sufficient for us to just make sure it's single digit.)
2322                 if (party > 0 && party < 10) {
2323                     sprintf(cmd, "AT+CHLD=2%d", party);
2324                     at_send_command(cmd, NULL);
2325                     RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2326                 } else {
2327                     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2328                 }
2329             }
2330             break;
2331
2332         case RIL_REQUEST_SIGNAL_STRENGTH:
2333             requestSignalStrength(data, datalen, t);
2334             break;
2335         case RIL_REQUEST_VOICE_REGISTRATION_STATE:
2336         case RIL_REQUEST_DATA_REGISTRATION_STATE:
2337             requestRegistrationState(request, data, datalen, t);
2338             break;
2339         case RIL_REQUEST_OPERATOR:
2340             requestOperator(data, datalen, t);
2341             break;
2342         case RIL_REQUEST_RADIO_POWER:
2343             requestRadioPower(data, datalen, t);
2344             break;
2345         case RIL_REQUEST_DTMF: {
2346             char c = ((char *)data)[0];
2347             char *cmd;
2348             asprintf(&cmd, "AT+VTS=%c", (int)c);
2349             at_send_command(cmd, NULL);
2350             free(cmd);
2351             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2352             break;
2353         }
2354         case RIL_REQUEST_SEND_SMS:
2355         case RIL_REQUEST_SEND_SMS_EXPECT_MORE:
2356             requestSendSMS(data, datalen, t);
2357             break;
2358         case RIL_REQUEST_CDMA_SEND_SMS:
2359             requestCdmaSendSMS(data, datalen, t);
2360             break;
2361         case RIL_REQUEST_IMS_SEND_SMS:
2362             requestImsSendSMS(data, datalen, t);
2363             break;
2364         case RIL_REQUEST_SIM_OPEN_CHANNEL:
2365             requestSimOpenChannel(data, datalen, t);
2366             break;
2367         case RIL_REQUEST_SIM_CLOSE_CHANNEL:
2368             requestSimCloseChannel(data, datalen, t);
2369             break;
2370         case RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL:
2371             requestSimTransmitApduChannel(data, datalen, t);
2372             break;
2373         case RIL_REQUEST_SETUP_DATA_CALL:
2374             requestSetupDataCall(data, datalen, t);
2375             break;
2376         case RIL_REQUEST_SMS_ACKNOWLEDGE:
2377             requestSMSAcknowledge(data, datalen, t);
2378             break;
2379
2380         case RIL_REQUEST_GET_IMSI:
2381             p_response = NULL;
2382             err = at_send_command_numeric("AT+CIMI", &p_response);
2383
2384             if (err < 0 || p_response->success == 0) {
2385                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2386             } else {
2387                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
2388                     p_response->p_intermediates->line, sizeof(char *));
2389             }
2390             at_response_free(p_response);
2391             break;
2392
2393         case RIL_REQUEST_GET_IMEI:
2394             p_response = NULL;
2395             err = at_send_command_numeric("AT+CGSN", &p_response);
2396
2397             if (err < 0 || p_response->success == 0) {
2398                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2399             } else {
2400                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
2401                     p_response->p_intermediates->line, sizeof(char *));
2402             }
2403             at_response_free(p_response);
2404             break;
2405
2406         case RIL_REQUEST_SIM_IO:
2407             requestSIM_IO(data,datalen,t);
2408             break;
2409
2410         case RIL_REQUEST_SEND_USSD:
2411             requestSendUSSD(data, datalen, t);
2412             break;
2413
2414         case RIL_REQUEST_CANCEL_USSD:
2415             p_response = NULL;
2416             err = at_send_command_numeric("AT+CUSD=2", &p_response);
2417
2418             if (err < 0 || p_response->success == 0) {
2419                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2420             } else {
2421                 RIL_onRequestComplete(t, RIL_E_SUCCESS,
2422                     p_response->p_intermediates->line, sizeof(char *));
2423             }
2424             at_response_free(p_response);
2425             break;
2426
2427         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
2428             at_send_command("AT+COPS=0", NULL);
2429             break;
2430
2431         case RIL_REQUEST_DATA_CALL_LIST:
2432             requestDataCallList(data, datalen, t);
2433             break;
2434
2435         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
2436             requestQueryNetworkSelectionMode(data, datalen, t);
2437             break;
2438
2439         case RIL_REQUEST_OEM_HOOK_RAW:
2440             // echo back data
2441             RIL_onRequestComplete(t, RIL_E_SUCCESS, data, datalen);
2442             break;
2443
2444
2445         case RIL_REQUEST_OEM_HOOK_STRINGS: {
2446             int i;
2447             const char ** cur;
2448
2449             RLOGD("got OEM_HOOK_STRINGS: 0x%8p %lu", data, (long)datalen);
2450
2451
2452             for (i = (datalen / sizeof (char *)), cur = (const char **)data ;
2453                     i > 0 ; cur++, i --) {
2454                 RLOGD("> '%s'", *cur);
2455             }
2456
2457             // echo back strings
2458             RIL_onRequestComplete(t, RIL_E_SUCCESS, data, datalen);
2459             break;
2460         }
2461
2462         case RIL_REQUEST_WRITE_SMS_TO_SIM:
2463             requestWriteSmsToSim(data, datalen, t);
2464             break;
2465
2466         case RIL_REQUEST_DELETE_SMS_ON_SIM: {
2467             char * cmd;
2468             p_response = NULL;
2469             asprintf(&cmd, "AT+CMGD=%d", ((int *)data)[0]);
2470             err = at_send_command(cmd, &p_response);
2471             free(cmd);
2472             if (err < 0 || p_response->success == 0) {
2473                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2474             } else {
2475                 RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2476             }
2477             at_response_free(p_response);
2478             break;
2479         }
2480
2481         case RIL_REQUEST_ENTER_SIM_PIN:
2482         case RIL_REQUEST_ENTER_SIM_PUK:
2483         case RIL_REQUEST_ENTER_SIM_PIN2:
2484         case RIL_REQUEST_ENTER_SIM_PUK2:
2485         case RIL_REQUEST_CHANGE_SIM_PIN:
2486         case RIL_REQUEST_CHANGE_SIM_PIN2:
2487             requestEnterSimPin(data, datalen, t);
2488             break;
2489
2490         case RIL_REQUEST_IMS_REGISTRATION_STATE: {
2491             int reply[2];
2492             //0==unregistered, 1==registered
2493             reply[0] = s_ims_registered;
2494
2495             //to be used when changed to include service supporated info
2496             //reply[1] = s_ims_services;
2497
2498             // FORMAT_3GPP(1) vs FORMAT_3GPP2(2);
2499             reply[1] = s_ims_format;
2500
2501             RLOGD("IMS_REGISTRATION=%d, format=%d ",
2502                     reply[0], reply[1]);
2503             if (reply[1] != -1) {
2504                 RIL_onRequestComplete(t, RIL_E_SUCCESS, reply, sizeof(reply));
2505             } else {
2506                 RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2507             }
2508             break;
2509         }
2510
2511         case RIL_REQUEST_VOICE_RADIO_TECH:
2512             {
2513                 int tech = techFromModemType(TECH(sMdmInfo));
2514                 if (tech < 0 )
2515                     RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
2516                 else
2517                     RIL_onRequestComplete(t, RIL_E_SUCCESS, &tech, sizeof(tech));
2518             }
2519             break;
2520         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
2521             requestSetPreferredNetworkType(request, data, datalen, t);
2522             break;
2523
2524         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
2525             requestGetPreferredNetworkType(request, data, datalen, t);
2526             break;
2527
2528         case RIL_REQUEST_GET_CELL_INFO_LIST:
2529             requestGetCellInfoList(data, datalen, t);
2530             break;
2531
2532         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
2533             requestSetCellInfoListRate(data, datalen, t);
2534             break;
2535
2536         case RIL_REQUEST_GET_HARDWARE_CONFIG:
2537             requestGetHardwareConfig(data, datalen, t);
2538             break;
2539
2540         case RIL_REQUEST_SHUTDOWN:
2541             requestShutdown(t);
2542             break;
2543
2544         case RIL_REQUEST_QUERY_TTY_MODE:
2545             requestGetTtyMode(data, datalen, t);
2546             break;
2547
2548         case RIL_REQUEST_GET_RADIO_CAPABILITY:
2549             requestGetRadioCapability(data, datalen, t);
2550             break;
2551
2552         case RIL_REQUEST_GET_MUTE:
2553             requestGetMute(data, datalen, t);
2554             break;
2555
2556         case RIL_REQUEST_SET_INITIAL_ATTACH_APN:
2557         case RIL_REQUEST_ALLOW_DATA:
2558         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION:
2559         case RIL_REQUEST_SET_CLIR:
2560         case RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION:
2561         case RIL_REQUEST_SET_BAND_MODE:
2562         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE:
2563         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
2564         case RIL_REQUEST_SET_LOCATION_UPDATES:
2565         case RIL_REQUEST_SET_TTY_MODE:
2566         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:
2567             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2568             break;
2569
2570         case RIL_REQUEST_BASEBAND_VERSION:
2571             requestCdmaBaseBandVersion(request, data, datalen, t);
2572             break;
2573
2574         case RIL_REQUEST_DEVICE_IDENTITY:
2575             requestCdmaDeviceIdentity(request, data, datalen, t);
2576             break;
2577
2578         case RIL_REQUEST_CDMA_SUBSCRIPTION:
2579             requestCdmaSubscription(request, data, datalen, t);
2580             break;
2581
2582         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
2583             requestCdmaGetSubscriptionSource(request, data, datalen, t);
2584             break;
2585
2586         /* CDMA Specific Requests */
2587         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
2588             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2589                 requestCdmaSetSubscriptionSource(request, data, datalen, t);
2590                 break;
2591             } // Fall-through if tech is not cdma
2592
2593         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:
2594             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2595                 requestCdmaGetRoamingPreference(request, data, datalen, t);
2596                 break;
2597             } // Fall-through if tech is not cdma
2598
2599         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
2600             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2601                 requestCdmaSetRoamingPreference(request, data, datalen, t);
2602                 break;
2603             } // Fall-through if tech is not cdma
2604
2605         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
2606             if (TECH_BIT(sMdmInfo) == MDM_CDMA) {
2607                 requestExitEmergencyMode(data, datalen, t);
2608                 break;
2609             } // Fall-through if tech is not cdma
2610
2611             // Fall-through to here when the request is specific to CDMA, but
2612             // our tech is not CDMA. VTS tests expect us to silently do nothing.
2613             RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
2614             break;
2615
2616         default:
2617             RLOGD("Request not supported. Tech: %d",TECH(sMdmInfo));
2618             RIL_onRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
2619             break;
2620     }
2621 }
2622
2623 /**
2624  * Synchronous call from the RIL to us to return current radio state.
2625  * RADIO_STATE_UNAVAILABLE should be the initial state.
2626  */
2627 static RIL_RadioState
2628 currentState()
2629 {
2630     return sState;
2631 }
2632 /**
2633  * Call from RIL to us to find out whether a specific request code
2634  * is supported by this implementation.
2635  *
2636  * Return 1 for "supported" and 0 for "unsupported"
2637  */
2638
2639 static int
2640 onSupports (int requestCode __unused)
2641 {
2642     //@@@ todo
2643
2644     return 1;
2645 }
2646
2647 static void onCancel (RIL_Token t __unused)
2648 {
2649     //@@@todo
2650
2651 }
2652
2653 static const char * getVersion(void)
2654 {
2655     return "android reference-ril 1.0";
2656 }
2657
2658 static void
2659 setRadioTechnology(ModemInfo *mdm, int newtech)
2660 {
2661     RLOGD("setRadioTechnology(%d)", newtech);
2662
2663     int oldtech = TECH(mdm);
2664
2665     if (newtech != oldtech) {
2666         RLOGD("Tech change (%d => %d)", oldtech, newtech);
2667         TECH(mdm) = newtech;
2668         if (techFromModemType(newtech) != techFromModemType(oldtech)) {
2669             int tech = techFromModemType(TECH(sMdmInfo));
2670             if (tech > 0 ) {
2671                 RIL_onUnsolicitedResponse(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
2672                                           &tech, sizeof(tech));
2673             }
2674         }
2675     }
2676 }
2677
2678 static void
2679 setRadioState(RIL_RadioState newState)
2680 {
2681     RLOGD("setRadioState(%d)", newState);
2682     RIL_RadioState oldState;
2683
2684     pthread_mutex_lock(&s_state_mutex);
2685
2686     oldState = sState;
2687
2688     if (s_closed > 0) {
2689         // If we're closed, the only reasonable state is
2690         // RADIO_STATE_UNAVAILABLE
2691         // This is here because things on the main thread
2692         // may attempt to change the radio state after the closed
2693         // event happened in another thread
2694         newState = RADIO_STATE_UNAVAILABLE;
2695     }
2696
2697     if (sState != newState || s_closed > 0) {
2698         sState = newState;
2699
2700         pthread_cond_broadcast (&s_state_cond);
2701     }
2702
2703     pthread_mutex_unlock(&s_state_mutex);
2704
2705
2706     /* do these outside of the mutex */
2707     if (sState != oldState) {
2708         RIL_onUnsolicitedResponse (RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
2709                                     NULL, 0);
2710         // Sim state can change as result of radio state change
2711         RIL_onUnsolicitedResponse (RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED,
2712                                     NULL, 0);
2713
2714         /* FIXME onSimReady() and onRadioPowerOn() cannot be called
2715          * from the AT reader thread
2716          * Currently, this doesn't happen, but if that changes then these
2717          * will need to be dispatched on the request thread
2718          */
2719         if (sState == RADIO_STATE_ON) {
2720             onRadioPowerOn();
2721         }
2722     }
2723 }
2724
2725 /** Returns RUIM_NOT_READY on error */
2726 static SIM_Status
2727 getRUIMStatus()
2728 {
2729     ATResponse *p_response = NULL;
2730     int err;
2731     int ret;
2732     char *cpinLine;
2733     char *cpinResult;
2734
2735     if (sState == RADIO_STATE_OFF || sState == RADIO_STATE_UNAVAILABLE) {
2736         ret = SIM_NOT_READY;
2737         goto done;
2738     }
2739
2740     err = at_send_command_singleline("AT+CPIN?", "+CPIN:", &p_response);
2741
2742     if (err != 0) {
2743         ret = SIM_NOT_READY;
2744         goto done;
2745     }
2746
2747     switch (at_get_cme_error(p_response)) {
2748         case CME_SUCCESS:
2749             break;
2750
2751         case CME_SIM_NOT_INSERTED:
2752             ret = SIM_ABSENT;
2753             goto done;
2754
2755         default:
2756             ret = SIM_NOT_READY;
2757             goto done;
2758     }
2759
2760     /* CPIN? has succeeded, now look at the result */
2761
2762     cpinLine = p_response->p_intermediates->line;
2763     err = at_tok_start (&cpinLine);
2764
2765     if (err < 0) {
2766         ret = SIM_NOT_READY;
2767         goto done;
2768     }
2769
2770     err = at_tok_nextstr(&cpinLine, &cpinResult);
2771
2772     if (err < 0) {
2773         ret = SIM_NOT_READY;
2774         goto done;
2775     }
2776
2777     if (0 == strcmp (cpinResult, "SIM PIN")) {
2778         ret = SIM_PIN;
2779         goto done;
2780     } else if (0 == strcmp (cpinResult, "SIM PUK")) {
2781         ret = SIM_PUK;
2782         goto done;
2783     } else if (0 == strcmp (cpinResult, "PH-NET PIN")) {
2784         return SIM_NETWORK_PERSONALIZATION;
2785     } else if (0 != strcmp (cpinResult, "READY"))  {
2786         /* we're treating unsupported lock types as "sim absent" */
2787         ret = SIM_ABSENT;
2788         goto done;
2789     }
2790
2791     at_response_free(p_response);
2792     p_response = NULL;
2793     cpinResult = NULL;
2794
2795     ret = SIM_READY;
2796
2797 done:
2798     at_response_free(p_response);
2799     return ret;
2800 }
2801
2802 /** Returns SIM_NOT_READY on error */
2803 static SIM_Status
2804 getSIMStatus()
2805 {
2806     ATResponse *p_response = NULL;
2807     int err;
2808     int ret;
2809     char *cpinLine;
2810     char *cpinResult;
2811
2812     RLOGD("getSIMStatus(). sState: %d",sState);
2813     err = at_send_command_singleline("AT+CPIN?", "+CPIN:", &p_response);
2814
2815     if (err != 0) {
2816         ret = SIM_NOT_READY;
2817         goto done;
2818     }
2819
2820     switch (at_get_cme_error(p_response)) {
2821         case CME_SUCCESS:
2822             break;
2823
2824         case CME_SIM_NOT_INSERTED:
2825             ret = SIM_ABSENT;
2826             goto done;
2827
2828         default:
2829             ret = SIM_NOT_READY;
2830             goto done;
2831     }
2832
2833     /* CPIN? has succeeded, now look at the result */
2834
2835     cpinLine = p_response->p_intermediates->line;
2836     err = at_tok_start (&cpinLine);
2837
2838     if (err < 0) {
2839         ret = SIM_NOT_READY;
2840         goto done;
2841     }
2842
2843     err = at_tok_nextstr(&cpinLine, &cpinResult);
2844
2845     if (err < 0) {
2846         ret = SIM_NOT_READY;
2847         goto done;
2848     }
2849
2850     if (0 == strcmp (cpinResult, "SIM PIN")) {
2851         ret = SIM_PIN;
2852         goto done;
2853     } else if (0 == strcmp (cpinResult, "SIM PUK")) {
2854         ret = SIM_PUK;
2855         goto done;
2856     } else if (0 == strcmp (cpinResult, "PH-NET PIN")) {
2857         return SIM_NETWORK_PERSONALIZATION;
2858     } else if (0 != strcmp (cpinResult, "READY"))  {
2859         /* we're treating unsupported lock types as "sim absent" */
2860         ret = SIM_ABSENT;
2861         goto done;
2862     }
2863
2864     at_response_free(p_response);
2865     p_response = NULL;
2866     cpinResult = NULL;
2867
2868     ret = (sState == RADIO_STATE_ON) ? SIM_READY : SIM_NOT_READY;
2869
2870 done:
2871     at_response_free(p_response);
2872     return ret;
2873 }
2874
2875
2876 /**
2877  * Get the current card status.
2878  *
2879  * This must be freed using freeCardStatus.
2880  * @return: On success returns RIL_E_SUCCESS
2881  */
2882 static int getCardStatus(RIL_CardStatus_v6 **pp_card_status) {
2883     static RIL_AppStatus app_status_array[] = {
2884         // SIM_ABSENT = 0
2885         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
2886           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2887         // SIM_NOT_READY = 1
2888         { RIL_APPTYPE_SIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
2889           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2890         // SIM_READY = 2
2891         { RIL_APPTYPE_SIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
2892           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2893         // SIM_PIN = 3
2894         { RIL_APPTYPE_SIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
2895           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
2896         // SIM_PUK = 4
2897         { RIL_APPTYPE_SIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
2898           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
2899         // SIM_NETWORK_PERSONALIZATION = 5
2900         { RIL_APPTYPE_SIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
2901           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
2902         // RUIM_ABSENT = 6
2903         { RIL_APPTYPE_UNKNOWN, RIL_APPSTATE_UNKNOWN, RIL_PERSOSUBSTATE_UNKNOWN,
2904           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2905         // RUIM_NOT_READY = 7
2906         { RIL_APPTYPE_RUIM, RIL_APPSTATE_DETECTED, RIL_PERSOSUBSTATE_UNKNOWN,
2907           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2908         // RUIM_READY = 8
2909         { RIL_APPTYPE_RUIM, RIL_APPSTATE_READY, RIL_PERSOSUBSTATE_READY,
2910           NULL, NULL, 0, RIL_PINSTATE_UNKNOWN, RIL_PINSTATE_UNKNOWN },
2911         // RUIM_PIN = 9
2912         { RIL_APPTYPE_RUIM, RIL_APPSTATE_PIN, RIL_PERSOSUBSTATE_UNKNOWN,
2913           NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN },
2914         // RUIM_PUK = 10
2915         { RIL_APPTYPE_RUIM, RIL_APPSTATE_PUK, RIL_PERSOSUBSTATE_UNKNOWN,
2916           NULL, NULL, 0, RIL_PINSTATE_ENABLED_BLOCKED, RIL_PINSTATE_UNKNOWN },
2917         // RUIM_NETWORK_PERSONALIZATION = 11
2918         { RIL_APPTYPE_RUIM, RIL_APPSTATE_SUBSCRIPTION_PERSO, RIL_PERSOSUBSTATE_SIM_NETWORK,
2919            NULL, NULL, 0, RIL_PINSTATE_ENABLED_NOT_VERIFIED, RIL_PINSTATE_UNKNOWN }
2920     };
2921     RIL_CardState card_state;
2922     int num_apps;
2923
2924     int sim_status = getSIMStatus();
2925     if (sim_status == SIM_ABSENT) {
2926         card_state = RIL_CARDSTATE_ABSENT;
2927         num_apps = 0;
2928     } else {
2929         card_state = RIL_CARDSTATE_PRESENT;
2930         num_apps = 2;
2931     }
2932
2933     // Allocate and initialize base card status.
2934     RIL_CardStatus_v6 *p_card_status = malloc(sizeof(RIL_CardStatus_v6));
2935     p_card_status->card_state = card_state;
2936     p_card_status->universal_pin_state = RIL_PINSTATE_UNKNOWN;
2937     p_card_status->gsm_umts_subscription_app_index = -1;
2938     p_card_status->cdma_subscription_app_index = -1;
2939     p_card_status->ims_subscription_app_index = -1;
2940     p_card_status->num_applications = num_apps;
2941
2942     // Initialize application status
2943     int i;
2944     for (i = 0; i < RIL_CARD_MAX_APPS; i++) {
2945         p_card_status->applications[i] = app_status_array[SIM_ABSENT];
2946     }
2947
2948     // Pickup the appropriate application status
2949     // that reflects sim_status for gsm.
2950     if (num_apps != 0) {
2951         // Only support one app, gsm
2952         p_card_status->num_applications = 2;
2953         p_card_status->gsm_umts_subscription_app_index = 0;
2954         p_card_status->cdma_subscription_app_index = 1;
2955
2956         // Get the correct app status
2957         p_card_status->applications[0] = app_status_array[sim_status];
2958         p_card_status->applications[1] = app_status_array[sim_status + RUIM_ABSENT];
2959     }
2960
2961     *pp_card_status = p_card_status;
2962     return RIL_E_SUCCESS;
2963 }
2964
2965 /**
2966  * Free the card status returned by getCardStatus
2967  */
2968 static void freeCardStatus(RIL_CardStatus_v6 *p_card_status) {
2969     free(p_card_status);
2970 }
2971
2972 /**
2973  * SIM ready means any commands that access the SIM will work, including:
2974  *  AT+CPIN, AT+CSMS, AT+CNMI, AT+CRSM
2975  *  (all SMS-related commands)
2976  */
2977
2978 static void pollSIMState (void *param __unused)
2979 {
2980     ATResponse *p_response;
2981     int ret;
2982
2983     if (sState != RADIO_STATE_UNAVAILABLE) {
2984         // no longer valid to poll
2985         return;
2986     }
2987
2988     switch(getSIMStatus()) {
2989         case SIM_ABSENT:
2990         case SIM_PIN:
2991         case SIM_PUK:
2992         case SIM_NETWORK_PERSONALIZATION:
2993         default:
2994             RLOGI("SIM ABSENT or LOCKED");
2995             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
2996         return;
2997
2998         case SIM_NOT_READY:
2999             RIL_requestTimedCallback (pollSIMState, NULL, &TIMEVAL_SIMPOLL);
3000         return;
3001
3002         case SIM_READY:
3003             RLOGI("SIM_READY");
3004             onSIMReady();
3005             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
3006         return;
3007     }
3008 }
3009
3010 /** returns 1 if on, 0 if off, and -1 on error */
3011 static int isRadioOn()
3012 {
3013     ATResponse *p_response = NULL;
3014     int err;
3015     char *line;
3016     char ret;
3017
3018     err = at_send_command_singleline("AT+CFUN?", "+CFUN:", &p_response);
3019
3020     if (err < 0 || p_response->success == 0) {
3021         // assume radio is off
3022         goto error;
3023     }
3024
3025     line = p_response->p_intermediates->line;
3026
3027     err = at_tok_start(&line);
3028     if (err < 0) goto error;
3029
3030     err = at_tok_nextbool(&line, &ret);
3031     if (err < 0) goto error;
3032
3033     at_response_free(p_response);
3034
3035     return (int)ret;
3036
3037 error:
3038
3039     at_response_free(p_response);
3040     return -1;
3041 }
3042
3043 /**
3044  * Parse the response generated by a +CTEC AT command
3045  * The values read from the response are stored in current and preferred.
3046  * Both current and preferred may be null. The corresponding value is ignored in that case.
3047  *
3048  * @return: -1 if some error occurs (or if the modem doesn't understand the +CTEC command)
3049  *          1 if the response includes the current technology only
3050  *          0 if the response includes both current technology and preferred mode
3051  */
3052 int parse_technology_response( const char *response, int *current, int32_t *preferred )
3053 {
3054     int err;
3055     char *line, *p;
3056     int ct;
3057     int32_t pt = 0;
3058     char *str_pt;
3059
3060     line = p = strdup(response);
3061     RLOGD("Response: %s", line);
3062     err = at_tok_start(&p);
3063     if (err || !at_tok_hasmore(&p)) {
3064         RLOGD("err: %d. p: %s", err, p);
3065         free(line);
3066         return -1;
3067     }
3068
3069     err = at_tok_nextint(&p, &ct);
3070     if (err) {
3071         free(line);
3072         return -1;
3073     }
3074     if (current) *current = ct;
3075
3076     RLOGD("line remaining after int: %s", p);
3077
3078     err = at_tok_nexthexint(&p, &pt);
3079     if (err) {
3080         free(line);
3081         return 1;
3082     }
3083     if (preferred) {
3084         *preferred = pt;
3085     }
3086     free(line);
3087
3088     return 0;
3089 }
3090
3091 int query_supported_techs( ModemInfo *mdm __unused, int *supported )
3092 {
3093     ATResponse *p_response;
3094     int err, val, techs = 0;
3095     char *tok;
3096     char *line;
3097
3098     RLOGD("query_supported_techs");
3099     err = at_send_command_singleline("AT+CTEC=?", "+CTEC:", &p_response);
3100     if (err || !p_response->success)
3101         goto error;
3102     line = p_response->p_intermediates->line;
3103     err = at_tok_start(&line);
3104     if (err || !at_tok_hasmore(&line))
3105         goto error;
3106     while (!at_tok_nextint(&line, &val)) {
3107         techs |= ( 1 << val );
3108     }
3109     if (supported) *supported = techs;
3110     return 0;
3111 error:
3112     at_response_free(p_response);
3113     return -1;
3114 }
3115
3116 /**
3117  * query_ctec. Send the +CTEC AT command to the modem to query the current
3118  * and preferred modes. It leaves values in the addresses pointed to by
3119  * current and preferred. If any of those pointers are NULL, the corresponding value
3120  * is ignored, but the return value will still reflect if retreiving and parsing of the
3121  * values suceeded.
3122  *
3123  * @mdm Currently unused
3124  * @current A pointer to store the current mode returned by the modem. May be null.
3125  * @preferred A pointer to store the preferred mode returned by the modem. May be null.
3126  * @return -1 on error (or failure to parse)
3127  *         1 if only the current mode was returned by modem (or failed to parse preferred)
3128  *         0 if both current and preferred were returned correctly
3129  */
3130 int query_ctec(ModemInfo *mdm __unused, int *current, int32_t *preferred)
3131 {
3132     ATResponse *response = NULL;
3133     int err;
3134     int res;
3135
3136     RLOGD("query_ctec. current: %p, preferred: %p", current, preferred);
3137     err = at_send_command_singleline("AT+CTEC?", "+CTEC:", &response);
3138     if (!err && response->success) {
3139         res = parse_technology_response(response->p_intermediates->line, current, preferred);
3140         at_response_free(response);
3141         return res;
3142     }
3143     RLOGE("Error executing command: %d. response: %p. status: %d", err, response, response? response->success : -1);
3144     at_response_free(response);
3145     return -1;
3146 }
3147
3148 int is_multimode_modem(ModemInfo *mdm)
3149 {
3150     ATResponse *response;
3151     int err;
3152     char *line;
3153     int tech;
3154     int32_t preferred;
3155
3156     if (query_ctec(mdm, &tech, &preferred) == 0) {
3157         mdm->currentTech = tech;
3158         mdm->preferredNetworkMode = preferred;
3159         if (query_supported_techs(mdm, &mdm->supportedTechs)) {
3160             return 0;
3161         }
3162         return 1;
3163     }
3164     return 0;
3165 }
3166
3167 /**
3168  * Find out if our modem is GSM, CDMA or both (Multimode)
3169  */
3170 static void probeForModemMode(ModemInfo *info)
3171 {
3172     ATResponse *response;
3173     int err;
3174     assert (info);
3175     // Currently, our only known multimode modem is qemu's android modem,
3176     // which implements the AT+CTEC command to query and set mode.
3177     // Try that first
3178
3179     if (is_multimode_modem(info)) {
3180         RLOGI("Found Multimode Modem. Supported techs mask: %8.8x. Current tech: %d",
3181             info->supportedTechs, info->currentTech);
3182         return;
3183     }
3184
3185     /* Being here means that our modem is not multimode */
3186     info->isMultimode = 0;
3187
3188     /* CDMA Modems implement the AT+WNAM command */
3189     err = at_send_command_singleline("AT+WNAM","+WNAM:", &response);
3190     if (!err && response->success) {
3191         at_response_free(response);
3192         // TODO: find out if we really support EvDo
3193         info->supportedTechs = MDM_CDMA | MDM_EVDO;
3194         info->currentTech = MDM_CDMA;
3195         RLOGI("Found CDMA Modem");
3196         return;
3197     }
3198     if (!err) at_response_free(response);
3199     // TODO: find out if modem really supports WCDMA/LTE
3200     info->supportedTechs = MDM_GSM | MDM_WCDMA | MDM_LTE;
3201     info->currentTech = MDM_GSM;
3202     RLOGI("Found GSM Modem");
3203 }
3204
3205 /**
3206  * Initialize everything that can be configured while we're still in
3207  * AT+CFUN=0
3208  */
3209 static void initializeCallback(void *param __unused)
3210 {
3211     ATResponse *p_response = NULL;
3212     int err;
3213
3214     setRadioState (RADIO_STATE_OFF);
3215
3216     at_handshake();
3217
3218     probeForModemMode(sMdmInfo);
3219     /* note: we don't check errors here. Everything important will
3220        be handled in onATTimeout and onATReaderClosed */
3221
3222     /*  atchannel is tolerant of echo but it must */
3223     /*  have verbose result codes */
3224     at_send_command("ATE0Q0V1", NULL);
3225
3226     /*  No auto-answer */
3227     at_send_command("ATS0=0", NULL);
3228
3229     /*  Extended errors */
3230     at_send_command("AT+CMEE=1", NULL);
3231
3232     /*  Network registration events */
3233     err = at_send_command("AT+CREG=2", &p_response);
3234
3235     /* some handsets -- in tethered mode -- don't support CREG=2 */
3236     if (err < 0 || p_response->success == 0) {
3237         at_send_command("AT+CREG=1", NULL);
3238     }
3239
3240     at_response_free(p_response);
3241
3242     /*  GPRS registration events */
3243     at_send_command("AT+CGREG=1", NULL);
3244
3245     /*  Call Waiting notifications */
3246     at_send_command("AT+CCWA=1", NULL);
3247
3248     /*  Alternating voice/data off */
3249     at_send_command("AT+CMOD=0", NULL);
3250
3251     /*  Not muted */
3252     at_send_command("AT+CMUT=0", NULL);
3253
3254     /*  +CSSU unsolicited supp service notifications */
3255     at_send_command("AT+CSSN=0,1", NULL);
3256
3257     /*  no connected line identification */
3258     at_send_command("AT+COLP=0", NULL);
3259
3260     /*  HEX character set */
3261     at_send_command("AT+CSCS=\"HEX\"", NULL);
3262
3263     /*  USSD unsolicited */
3264     at_send_command("AT+CUSD=1", NULL);
3265
3266     /*  Enable +CGEV GPRS event notifications, but don't buffer */
3267     at_send_command("AT+CGEREP=1,0", NULL);
3268
3269     /*  SMS PDU mode */
3270     at_send_command("AT+CMGF=0", NULL);
3271
3272 #ifdef USE_TI_COMMANDS
3273
3274     at_send_command("AT%CPI=3", NULL);
3275
3276     /*  TI specific -- notifications when SMS is ready (currently ignored) */
3277     at_send_command("AT%CSTAT=1", NULL);
3278
3279 #endif /* USE_TI_COMMANDS */
3280
3281
3282     /* assume radio is off on error */
3283     if (isRadioOn() > 0) {
3284         setRadioState (RADIO_STATE_ON);
3285     }
3286 }
3287
3288 static void waitForClose()
3289 {
3290     pthread_mutex_lock(&s_state_mutex);
3291
3292     while (s_closed == 0) {
3293         pthread_cond_wait(&s_state_cond, &s_state_mutex);
3294     }
3295
3296     pthread_mutex_unlock(&s_state_mutex);
3297 }
3298
3299 static void sendUnsolImsNetworkStateChanged()
3300 {
3301 #if 0 // to be used when unsol is changed to return data.
3302     int reply[2];
3303     reply[0] = s_ims_registered;
3304     reply[1] = s_ims_services;
3305     reply[1] = s_ims_format;
3306 #endif
3307     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED,
3308             NULL, 0);
3309 }
3310
3311 /**
3312  * Called by atchannel when an unsolicited line appears
3313  * This is called on atchannel's reader thread. AT commands may
3314  * not be issued here
3315  */
3316 static void onUnsolicited (const char *s, const char *sms_pdu)
3317 {
3318     char *line = NULL, *p;
3319     int err;
3320
3321     /* Ignore unsolicited responses until we're initialized.
3322      * This is OK because the RIL library will poll for initial state
3323      */
3324     if (sState == RADIO_STATE_UNAVAILABLE) {
3325         return;
3326     }
3327
3328     if (strStartsWith(s, "%CTZV:")) {
3329         /* TI specific -- NITZ time */
3330         char *response;
3331
3332         line = p = strdup(s);
3333         at_tok_start(&p);
3334
3335         err = at_tok_nextstr(&p, &response);
3336
3337         if (err != 0) {
3338             RLOGE("invalid NITZ line %s\n", s);
3339         } else {
3340             RIL_onUnsolicitedResponse (
3341                 RIL_UNSOL_NITZ_TIME_RECEIVED,
3342                 response, strlen(response));
3343         }
3344         free(line);
3345     } else if (strStartsWith(s,"+CRING:")
3346                 || strStartsWith(s,"RING")
3347                 || strStartsWith(s,"NO CARRIER")
3348                 || strStartsWith(s,"+CCWA")
3349     ) {
3350         RIL_onUnsolicitedResponse (
3351             RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
3352             NULL, 0);
3353 #ifdef WORKAROUND_FAKE_CGEV
3354         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL); //TODO use new function
3355 #endif /* WORKAROUND_FAKE_CGEV */
3356     } else if (strStartsWith(s,"+CREG:")
3357                 || strStartsWith(s,"+CGREG:")
3358     ) {
3359         RIL_onUnsolicitedResponse (
3360             RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
3361             NULL, 0);
3362 #ifdef WORKAROUND_FAKE_CGEV
3363         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
3364 #endif /* WORKAROUND_FAKE_CGEV */
3365     } else if (strStartsWith(s, "+CMT:")) {
3366         RIL_onUnsolicitedResponse (
3367             RIL_UNSOL_RESPONSE_NEW_SMS,
3368             sms_pdu, strlen(sms_pdu));
3369     } else if (strStartsWith(s, "+CDS:")) {
3370         RIL_onUnsolicitedResponse (
3371             RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT,
3372             sms_pdu, strlen(sms_pdu));
3373     } else if (strStartsWith(s, "+CGEV:")) {
3374         /* Really, we can ignore NW CLASS and ME CLASS events here,
3375          * but right now we don't since extranous
3376          * RIL_UNSOL_DATA_CALL_LIST_CHANGED calls are tolerated
3377          */
3378         /* can't issue AT commands here -- call on main thread */
3379         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
3380 #ifdef WORKAROUND_FAKE_CGEV
3381     } else if (strStartsWith(s, "+CME ERROR: 150")) {
3382         RIL_requestTimedCallback (onDataCallListChanged, NULL, NULL);
3383 #endif /* WORKAROUND_FAKE_CGEV */
3384     } else if (strStartsWith(s, "+CTEC: ")) {
3385         int tech, mask;
3386         switch (parse_technology_response(s, &tech, NULL))
3387         {
3388             case -1: // no argument could be parsed.
3389                 RLOGE("invalid CTEC line %s\n", s);
3390                 break;
3391             case 1: // current mode correctly parsed
3392             case 0: // preferred mode correctly parsed
3393                 mask = 1 << tech;
3394                 if (mask != MDM_GSM && mask != MDM_CDMA &&
3395                      mask != MDM_WCDMA && mask != MDM_LTE) {
3396                     RLOGE("Unknown technology %d\n", tech);
3397                 } else {
3398                     setRadioTechnology(sMdmInfo, tech);
3399                 }
3400                 break;
3401         }
3402     } else if (strStartsWith(s, "+CCSS: ")) {
3403         int source = 0;
3404         line = p = strdup(s);
3405         if (!line) {
3406             RLOGE("+CCSS: Unable to allocate memory");
3407             return;
3408         }
3409         if (at_tok_start(&p) < 0) {
3410             free(line);
3411             return;
3412         }
3413         if (at_tok_nextint(&p, &source) < 0) {
3414             RLOGE("invalid +CCSS response: %s", line);
3415             free(line);
3416             return;
3417         }
3418         SSOURCE(sMdmInfo) = source;
3419         RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
3420                                   &source, sizeof(source));
3421     } else if (strStartsWith(s, "+WSOS: ")) {
3422         char state = 0;
3423         int unsol;
3424         line = p = strdup(s);
3425         if (!line) {
3426             RLOGE("+WSOS: Unable to allocate memory");
3427             return;
3428         }
3429         if (at_tok_start(&p) < 0) {
3430             free(line);
3431             return;
3432         }
3433         if (at_tok_nextbool(&p, &state) < 0) {
3434             RLOGE("invalid +WSOS response: %s", line);
3435             free(line);
3436             return;
3437         }
3438         free(line);
3439
3440         unsol = state ?
3441                 RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE : RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE;
3442
3443         RIL_onUnsolicitedResponse(unsol, NULL, 0);
3444
3445     } else if (strStartsWith(s, "+WPRL: ")) {
3446         int version = -1;
3447         line = p = strdup(s);
3448         if (!line) {
3449             RLOGE("+WPRL: Unable to allocate memory");
3450             return;
3451         }
3452         if (at_tok_start(&p) < 0) {
3453             RLOGE("invalid +WPRL response: %s", s);
3454             free(line);
3455             return;
3456         }
3457         if (at_tok_nextint(&p, &version) < 0) {
3458             RLOGE("invalid +WPRL response: %s", s);
3459             free(line);
3460             return;
3461         }
3462         free(line);
3463         RIL_onUnsolicitedResponse(RIL_UNSOL_CDMA_PRL_CHANGED, &version, sizeof(version));
3464     } else if (strStartsWith(s, "+CFUN: 0")) {
3465         setRadioState(RADIO_STATE_OFF);
3466     }
3467 }
3468
3469 /* Called on command or reader thread */
3470 static void onATReaderClosed()
3471 {
3472     RLOGI("AT channel closed\n");
3473     at_close();
3474     s_closed = 1;
3475
3476     setRadioState (RADIO_STATE_UNAVAILABLE);
3477 }
3478
3479 /* Called on command thread */
3480 static void onATTimeout()
3481 {
3482     RLOGI("AT channel timeout; closing\n");
3483     at_close();
3484
3485     s_closed = 1;
3486
3487     /* FIXME cause a radio reset here */
3488
3489     setRadioState (RADIO_STATE_UNAVAILABLE);
3490 }
3491
3492 /* Called to pass hardware configuration information to telephony
3493  * framework.
3494  */
3495 static void setHardwareConfiguration(int num, RIL_HardwareConfig *cfg)
3496 {
3497    RIL_onUnsolicitedResponse(RIL_UNSOL_HARDWARE_CONFIG_CHANGED, cfg, num*sizeof(*cfg));
3498 }
3499
3500 static void usage(char *s __unused)
3501 {
3502 #ifdef RIL_SHLIB
3503     fprintf(stderr, "reference-ril requires: -p <tcp port> or -d /dev/tty_device\n");
3504 #else
3505     fprintf(stderr, "usage: %s [-p <tcp port>] [-d /dev/tty_device]\n", s);
3506     exit(-1);
3507 #endif
3508 }
3509
3510 static void *
3511 mainLoop(void *param __unused)
3512 {
3513     int fd;
3514     int ret;
3515
3516     AT_DUMP("== ", "entering mainLoop()", -1 );
3517     at_set_on_reader_closed(onATReaderClosed);
3518     at_set_on_timeout(onATTimeout);
3519
3520     for (;;) {
3521         fd = -1;
3522         while  (fd < 0) {
3523             if (isInEmulator()) {
3524                 fd = qemu_pipe_open("pipe:qemud:gsm");
3525             } else if (s_port > 0) {
3526                 fd = socket_network_client("localhost", s_port, SOCK_STREAM);
3527             } else if (s_device_socket) {
3528                 fd = socket_local_client(s_device_path,
3529                                          ANDROID_SOCKET_NAMESPACE_FILESYSTEM,
3530                                          SOCK_STREAM);
3531             } else if (s_device_path != NULL) {
3532                 fd = open (s_device_path, O_RDWR);
3533                 if ( fd >= 0 && !memcmp( s_device_path, "/dev/ttyS", 9 ) ) {
3534                     /* disable echo on serial ports */
3535                     struct termios  ios;
3536                     tcgetattr( fd, &ios );
3537                     ios.c_lflag = 0;  /* disable ECHO, ICANON, etc... */
3538                     tcsetattr( fd, TCSANOW, &ios );
3539                 }
3540             }
3541
3542             if (fd < 0) {
3543                 perror ("opening AT interface. retrying...");
3544                 sleep(10);
3545                 /* never returns */
3546             }
3547         }
3548
3549         s_closed = 0;
3550         ret = at_open(fd, onUnsolicited);
3551
3552         if (ret < 0) {
3553             RLOGE ("AT error %d on at_open\n", ret);
3554             return 0;
3555         }
3556
3557         RIL_requestTimedCallback(initializeCallback, NULL, &TIMEVAL_0);
3558
3559         // Give initializeCallback a chance to dispatched, since
3560         // we don't presently have a cancellation mechanism
3561         sleep(1);
3562
3563         waitForClose();
3564         RLOGI("Re-opening after close");
3565     }
3566 }
3567
3568 #ifdef RIL_SHLIB
3569
3570 pthread_t s_tid_mainloop;
3571
3572 const RIL_RadioFunctions *RIL_Init(const struct RIL_Env *env, int argc, char **argv)
3573 {
3574     int ret;
3575     int fd = -1;
3576     int opt;
3577     pthread_attr_t attr;
3578
3579     s_rilenv = env;
3580
3581     while ( -1 != (opt = getopt(argc, argv, "p:d:s:c:"))) {
3582         switch (opt) {
3583             case 'p':
3584                 s_port = atoi(optarg);
3585                 if (s_port == 0) {
3586                     usage(argv[0]);
3587                     return NULL;
3588                 }
3589                 RLOGI("Opening loopback port %d\n", s_port);
3590             break;
3591
3592             case 'd':
3593                 s_device_path = optarg;
3594                 RLOGI("Opening tty device %s\n", s_device_path);
3595             break;
3596
3597             case 's':
3598                 s_device_path   = optarg;
3599                 s_device_socket = 1;
3600                 RLOGI("Opening socket %s\n", s_device_path);
3601             break;
3602
3603             case 'c':
3604                 RLOGI("Client id received %s\n", optarg);
3605             break;
3606
3607             default:
3608                 usage(argv[0]);
3609                 return NULL;
3610         }
3611     }
3612
3613     if (s_port < 0 && s_device_path == NULL && !isInEmulator()) {
3614         usage(argv[0]);
3615         return NULL;
3616     }
3617
3618     sMdmInfo = calloc(1, sizeof(ModemInfo));
3619     if (!sMdmInfo) {
3620         RLOGE("Unable to alloc memory for ModemInfo");
3621         return NULL;
3622     }
3623     pthread_attr_init (&attr);
3624     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3625     ret = pthread_create(&s_tid_mainloop, &attr, mainLoop, NULL);
3626
3627     return &s_callbacks;
3628 }
3629 #else /* RIL_SHLIB */
3630 int main (int argc, char **argv)
3631 {
3632     int ret;
3633     int fd = -1;
3634     int opt;
3635
3636     while ( -1 != (opt = getopt(argc, argv, "p:d:"))) {
3637         switch (opt) {
3638             case 'p':
3639                 s_port = atoi(optarg);
3640                 if (s_port == 0) {
3641                     usage(argv[0]);
3642                 }
3643                 RLOGI("Opening loopback port %d\n", s_port);
3644             break;
3645
3646             case 'd':
3647                 s_device_path = optarg;
3648                 RLOGI("Opening tty device %s\n", s_device_path);
3649             break;
3650
3651             case 's':
3652                 s_device_path   = optarg;
3653                 s_device_socket = 1;
3654                 RLOGI("Opening socket %s\n", s_device_path);
3655             break;
3656
3657             default:
3658                 usage(argv[0]);
3659         }
3660     }
3661
3662     if (s_port < 0 && s_device_path == NULL && !isInEmulator()) {
3663         usage(argv[0]);
3664     }
3665
3666     RIL_register(&s_callbacks);
3667
3668     mainLoop(NULL);
3669
3670     return 0;
3671 }
3672
3673 #endif /* RIL_SHLIB */