OSDN Git Service

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