OSDN Git Service

Add support for CellInfo RIL commands.
[android-x86/hardware-ril.git] / libril / ril.cpp
1 /* //device/libs/telephony/ril.cpp
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 #define LOG_TAG "RILC"
19
20 #include <hardware_legacy/power.h>
21
22 #include <telephony/ril.h>
23 #include <telephony/ril_cdma_sms.h>
24 #include <cutils/sockets.h>
25 #include <cutils/jstring.h>
26 #include <cutils/record_stream.h>
27 #include <utils/Log.h>
28 #include <utils/SystemClock.h>
29 #include <pthread.h>
30 #include <binder/Parcel.h>
31 #include <cutils/jstring.h>
32
33 #include <sys/types.h>
34 #include <sys/limits.h>
35 #include <pwd.h>
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <stdarg.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <time.h>
44 #include <errno.h>
45 #include <assert.h>
46 #include <ctype.h>
47 #include <alloca.h>
48 #include <sys/un.h>
49 #include <assert.h>
50 #include <netinet/in.h>
51 #include <cutils/properties.h>
52
53 #include <ril_event.h>
54
55 namespace android {
56
57 #define PHONE_PROCESS "radio"
58
59 #define SOCKET_NAME_RIL "rild"
60 #define SOCKET_NAME_RIL_DEBUG "rild-debug"
61
62 #define ANDROID_WAKE_LOCK_NAME "radio-interface"
63
64
65 #define PROPERTY_RIL_IMPL "gsm.version.ril-impl"
66
67 // match with constant in RIL.java
68 #define MAX_COMMAND_BYTES (8 * 1024)
69
70 // Basically: memset buffers that the client library
71 // shouldn't be using anymore in an attempt to find
72 // memory usage issues sooner.
73 #define MEMSET_FREED 1
74
75 #define NUM_ELEMS(a)     (sizeof (a) / sizeof (a)[0])
76
77 #define MIN(a,b) ((a)<(b) ? (a) : (b))
78
79 /* Constants for response types */
80 #define RESPONSE_SOLICITED 0
81 #define RESPONSE_UNSOLICITED 1
82
83 /* Negative values for private RIL errno's */
84 #define RIL_ERRNO_INVALID_RESPONSE -1
85
86 // request, response, and unsolicited msg print macro
87 #define PRINTBUF_SIZE 8096
88
89 // Enable RILC log
90 #define RILC_LOG 0
91
92 #if RILC_LOG
93     #define startRequest           sprintf(printBuf, "(")
94     #define closeRequest           sprintf(printBuf, "%s)", printBuf)
95     #define printRequest(token, req)           \
96             RLOGD("[%04d]> %s %s", token, requestToString(req), printBuf)
97
98     #define startResponse           sprintf(printBuf, "%s {", printBuf)
99     #define closeResponse           sprintf(printBuf, "%s}", printBuf)
100     #define printResponse           RLOGD("%s", printBuf)
101
102     #define clearPrintBuf           printBuf[0] = 0
103     #define removeLastChar          printBuf[strlen(printBuf)-1] = 0
104     #define appendPrintBuf(x...)    sprintf(printBuf, x)
105 #else
106     #define startRequest
107     #define closeRequest
108     #define printRequest(token, req)
109     #define startResponse
110     #define closeResponse
111     #define printResponse
112     #define clearPrintBuf
113     #define removeLastChar
114     #define appendPrintBuf(x...)
115 #endif
116
117 enum WakeType {DONT_WAKE, WAKE_PARTIAL};
118
119 typedef struct {
120     int requestNumber;
121     void (*dispatchFunction) (Parcel &p, struct RequestInfo *pRI);
122     int(*responseFunction) (Parcel &p, void *response, size_t responselen);
123 } CommandInfo;
124
125 typedef struct {
126     int requestNumber;
127     int (*responseFunction) (Parcel &p, void *response, size_t responselen);
128     WakeType wakeType;
129 } UnsolResponseInfo;
130
131 typedef struct RequestInfo {
132     int32_t token;      //this is not RIL_Token
133     CommandInfo *pCI;
134     struct RequestInfo *p_next;
135     char cancelled;
136     char local;         // responses to local commands do not go back to command process
137 } RequestInfo;
138
139 typedef struct UserCallbackInfo {
140     RIL_TimedCallback p_callback;
141     void *userParam;
142     struct ril_event event;
143     struct UserCallbackInfo *p_next;
144 } UserCallbackInfo;
145
146
147 /*******************************************************************/
148
149 RIL_RadioFunctions s_callbacks = {0, NULL, NULL, NULL, NULL, NULL};
150 static int s_registerCalled = 0;
151
152 static pthread_t s_tid_dispatch;
153 static pthread_t s_tid_reader;
154 static int s_started = 0;
155
156 static int s_fdListen = -1;
157 static int s_fdCommand = -1;
158 static int s_fdDebug = -1;
159
160 static int s_fdWakeupRead;
161 static int s_fdWakeupWrite;
162
163 static struct ril_event s_commands_event;
164 static struct ril_event s_wakeupfd_event;
165 static struct ril_event s_listen_event;
166 static struct ril_event s_wake_timeout_event;
167 static struct ril_event s_debug_event;
168
169
170 static const struct timeval TIMEVAL_WAKE_TIMEOUT = {1,0};
171
172 static pthread_mutex_t s_pendingRequestsMutex = PTHREAD_MUTEX_INITIALIZER;
173 static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER;
174 static pthread_mutex_t s_startupMutex = PTHREAD_MUTEX_INITIALIZER;
175 static pthread_cond_t s_startupCond = PTHREAD_COND_INITIALIZER;
176
177 static pthread_mutex_t s_dispatchMutex = PTHREAD_MUTEX_INITIALIZER;
178 static pthread_cond_t s_dispatchCond = PTHREAD_COND_INITIALIZER;
179
180 static RequestInfo *s_pendingRequests = NULL;
181
182 static RequestInfo *s_toDispatchHead = NULL;
183 static RequestInfo *s_toDispatchTail = NULL;
184
185 static UserCallbackInfo *s_last_wake_timeout_info = NULL;
186
187 static void *s_lastNITZTimeData = NULL;
188 static size_t s_lastNITZTimeDataSize;
189
190 #if RILC_LOG
191     static char printBuf[PRINTBUF_SIZE];
192 #endif
193
194 /*******************************************************************/
195
196 static void dispatchVoid (Parcel& p, RequestInfo *pRI);
197 static void dispatchString (Parcel& p, RequestInfo *pRI);
198 static void dispatchStrings (Parcel& p, RequestInfo *pRI);
199 static void dispatchInts (Parcel& p, RequestInfo *pRI);
200 static void dispatchDial (Parcel& p, RequestInfo *pRI);
201 static void dispatchSIM_IO (Parcel& p, RequestInfo *pRI);
202 static void dispatchCallForward(Parcel& p, RequestInfo *pRI);
203 static void dispatchRaw(Parcel& p, RequestInfo *pRI);
204 static void dispatchSmsWrite (Parcel &p, RequestInfo *pRI);
205 static void dispatchDataCall (Parcel& p, RequestInfo *pRI);
206 static void dispatchVoiceRadioTech (Parcel& p, RequestInfo *pRI);
207 static void dispatchCdmaSubscriptionSource (Parcel& p, RequestInfo *pRI);
208
209 static void dispatchCdmaSms(Parcel &p, RequestInfo *pRI);
210 static void dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI);
211 static void dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI);
212 static void dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI);
213 static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI);
214 static int responseInts(Parcel &p, void *response, size_t responselen);
215 static int responseStrings(Parcel &p, void *response, size_t responselen);
216 static int responseString(Parcel &p, void *response, size_t responselen);
217 static int responseVoid(Parcel &p, void *response, size_t responselen);
218 static int responseCallList(Parcel &p, void *response, size_t responselen);
219 static int responseSMS(Parcel &p, void *response, size_t responselen);
220 static int responseSIM_IO(Parcel &p, void *response, size_t responselen);
221 static int responseCallForwards(Parcel &p, void *response, size_t responselen);
222 static int responseDataCallList(Parcel &p, void *response, size_t responselen);
223 static int responseSetupDataCall(Parcel &p, void *response, size_t responselen);
224 static int responseRaw(Parcel &p, void *response, size_t responselen);
225 static int responseSsn(Parcel &p, void *response, size_t responselen);
226 static int responseSimStatus(Parcel &p, void *response, size_t responselen);
227 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen);
228 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen);
229 static int responseCdmaSms(Parcel &p, void *response, size_t responselen);
230 static int responseCellList(Parcel &p, void *response, size_t responselen);
231 static int responseCdmaInformationRecords(Parcel &p,void *response, size_t responselen);
232 static int responseRilSignalStrength(Parcel &p,void *response, size_t responselen);
233 static int responseCallRing(Parcel &p, void *response, size_t responselen);
234 static int responseCdmaSignalInfoRecord(Parcel &p,void *response, size_t responselen);
235 static int responseCdmaCallWaiting(Parcel &p,void *response, size_t responselen);
236 static int responseSimRefresh(Parcel &p, void *response, size_t responselen);
237 static int responseCellInfoList(Parcel &p, void *response, size_t responselen);
238
239 static int decodeVoiceRadioTechnology (RIL_RadioState radioState);
240 static int decodeCdmaSubscriptionSource (RIL_RadioState radioState);
241 static RIL_RadioState processRadioState(RIL_RadioState newRadioState);
242
243 extern "C" const char * requestToString(int request);
244 extern "C" const char * failCauseToString(RIL_Errno);
245 extern "C" const char * callStateToString(RIL_CallState);
246 extern "C" const char * radioStateToString(RIL_RadioState);
247
248 #ifdef RIL_SHLIB
249 extern "C" void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
250                                 size_t datalen);
251 #endif
252
253 static UserCallbackInfo * internalRequestTimedCallback
254     (RIL_TimedCallback callback, void *param,
255         const struct timeval *relativeTime);
256
257 /** Index == requestNumber */
258 static CommandInfo s_commands[] = {
259 #include "ril_commands.h"
260 };
261
262 static UnsolResponseInfo s_unsolResponses[] = {
263 #include "ril_unsol_commands.h"
264 };
265
266 /* For older RILs that do not support new commands RIL_REQUEST_VOICE_RADIO_TECH and
267    RIL_UNSOL_VOICE_RADIO_TECH_CHANGED messages, decode the voice radio tech from
268    radio state message and store it. Every time there is a change in Radio State
269    check to see if voice radio tech changes and notify telephony
270  */
271 int voiceRadioTech = -1;
272
273 /* For older RILs that do not support new commands RIL_REQUEST_GET_CDMA_SUBSCRIPTION_SOURCE
274    and RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED messages, decode the subscription
275    source from radio state and store it. Every time there is a change in Radio State
276    check to see if subscription source changed and notify telephony
277  */
278 int cdmaSubscriptionSource = -1;
279
280 /* For older RILs that do not send RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, decode the
281    SIM/RUIM state from radio state and store it. Every time there is a change in Radio State,
282    check to see if SIM/RUIM status changed and notify telephony
283  */
284 int simRuimStatus = -1;
285
286 static char *
287 strdupReadString(Parcel &p) {
288     size_t stringlen;
289     const char16_t *s16;
290
291     s16 = p.readString16Inplace(&stringlen);
292
293     return strndup16to8(s16, stringlen);
294 }
295
296 static void writeStringToParcel(Parcel &p, const char *s) {
297     char16_t *s16;
298     size_t s16_len;
299     s16 = strdup8to16(s, &s16_len);
300     p.writeString16(s16, s16_len);
301     free(s16);
302 }
303
304
305 static void
306 memsetString (char *s) {
307     if (s != NULL) {
308         memset (s, 0, strlen(s));
309     }
310 }
311
312 void   nullParcelReleaseFunction (const uint8_t* data, size_t dataSize,
313                                     const size_t* objects, size_t objectsSize,
314                                         void* cookie) {
315     // do nothing -- the data reference lives longer than the Parcel object
316 }
317
318 /**
319  * To be called from dispatch thread
320  * Issue a single local request, ensuring that the response
321  * is not sent back up to the command process
322  */
323 static void
324 issueLocalRequest(int request, void *data, int len) {
325     RequestInfo *pRI;
326     int ret;
327
328     pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
329
330     pRI->local = 1;
331     pRI->token = 0xffffffff;        // token is not used in this context
332     pRI->pCI = &(s_commands[request]);
333
334     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
335     assert (ret == 0);
336
337     pRI->p_next = s_pendingRequests;
338     s_pendingRequests = pRI;
339
340     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
341     assert (ret == 0);
342
343     RLOGD("C[locl]> %s", requestToString(request));
344
345     s_callbacks.onRequest(request, data, len, pRI);
346 }
347
348
349
350 static int
351 processCommandBuffer(void *buffer, size_t buflen) {
352     Parcel p;
353     status_t status;
354     int32_t request;
355     int32_t token;
356     RequestInfo *pRI;
357     int ret;
358
359     p.setData((uint8_t *) buffer, buflen);
360
361     // status checked at end
362     status = p.readInt32(&request);
363     status = p.readInt32 (&token);
364
365     if (status != NO_ERROR) {
366         RLOGE("invalid request block");
367         return 0;
368     }
369
370     if (request < 1 || request >= (int32_t)NUM_ELEMS(s_commands)) {
371         RLOGE("unsupported request code %d token %d", request, token);
372         // FIXME this should perhaps return a response
373         return 0;
374     }
375
376
377     pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
378
379     pRI->token = token;
380     pRI->pCI = &(s_commands[request]);
381
382     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
383     assert (ret == 0);
384
385     pRI->p_next = s_pendingRequests;
386     s_pendingRequests = pRI;
387
388     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
389     assert (ret == 0);
390
391 /*    sLastDispatchedToken = token; */
392
393     pRI->pCI->dispatchFunction(p, pRI);
394
395     return 0;
396 }
397
398 static void
399 invalidCommandBlock (RequestInfo *pRI) {
400     RLOGE("invalid command block for token %d request %s",
401                 pRI->token, requestToString(pRI->pCI->requestNumber));
402 }
403
404 /** Callee expects NULL */
405 static void
406 dispatchVoid (Parcel& p, RequestInfo *pRI) {
407     clearPrintBuf;
408     printRequest(pRI->token, pRI->pCI->requestNumber);
409     s_callbacks.onRequest(pRI->pCI->requestNumber, NULL, 0, pRI);
410 }
411
412 /** Callee expects const char * */
413 static void
414 dispatchString (Parcel& p, RequestInfo *pRI) {
415     status_t status;
416     size_t datalen;
417     size_t stringlen;
418     char *string8 = NULL;
419
420     string8 = strdupReadString(p);
421
422     startRequest;
423     appendPrintBuf("%s%s", printBuf, string8);
424     closeRequest;
425     printRequest(pRI->token, pRI->pCI->requestNumber);
426
427     s_callbacks.onRequest(pRI->pCI->requestNumber, string8,
428                        sizeof(char *), pRI);
429
430 #ifdef MEMSET_FREED
431     memsetString(string8);
432 #endif
433
434     free(string8);
435     return;
436 invalid:
437     invalidCommandBlock(pRI);
438     return;
439 }
440
441 /** Callee expects const char ** */
442 static void
443 dispatchStrings (Parcel &p, RequestInfo *pRI) {
444     int32_t countStrings;
445     status_t status;
446     size_t datalen;
447     char **pStrings;
448
449     status = p.readInt32 (&countStrings);
450
451     if (status != NO_ERROR) {
452         goto invalid;
453     }
454
455     startRequest;
456     if (countStrings == 0) {
457         // just some non-null pointer
458         pStrings = (char **)alloca(sizeof(char *));
459         datalen = 0;
460     } else if (((int)countStrings) == -1) {
461         pStrings = NULL;
462         datalen = 0;
463     } else {
464         datalen = sizeof(char *) * countStrings;
465
466         pStrings = (char **)alloca(datalen);
467
468         for (int i = 0 ; i < countStrings ; i++) {
469             pStrings[i] = strdupReadString(p);
470             appendPrintBuf("%s%s,", printBuf, pStrings[i]);
471         }
472     }
473     removeLastChar;
474     closeRequest;
475     printRequest(pRI->token, pRI->pCI->requestNumber);
476
477     s_callbacks.onRequest(pRI->pCI->requestNumber, pStrings, datalen, pRI);
478
479     if (pStrings != NULL) {
480         for (int i = 0 ; i < countStrings ; i++) {
481 #ifdef MEMSET_FREED
482             memsetString (pStrings[i]);
483 #endif
484             free(pStrings[i]);
485         }
486
487 #ifdef MEMSET_FREED
488         memset(pStrings, 0, datalen);
489 #endif
490     }
491
492     return;
493 invalid:
494     invalidCommandBlock(pRI);
495     return;
496 }
497
498 /** Callee expects const int * */
499 static void
500 dispatchInts (Parcel &p, RequestInfo *pRI) {
501     int32_t count;
502     status_t status;
503     size_t datalen;
504     int *pInts;
505
506     status = p.readInt32 (&count);
507
508     if (status != NO_ERROR || count == 0) {
509         goto invalid;
510     }
511
512     datalen = sizeof(int) * count;
513     pInts = (int *)alloca(datalen);
514
515     startRequest;
516     for (int i = 0 ; i < count ; i++) {
517         int32_t t;
518
519         status = p.readInt32(&t);
520         pInts[i] = (int)t;
521         appendPrintBuf("%s%d,", printBuf, t);
522
523         if (status != NO_ERROR) {
524             goto invalid;
525         }
526    }
527    removeLastChar;
528    closeRequest;
529    printRequest(pRI->token, pRI->pCI->requestNumber);
530
531    s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<int *>(pInts),
532                        datalen, pRI);
533
534 #ifdef MEMSET_FREED
535     memset(pInts, 0, datalen);
536 #endif
537
538     return;
539 invalid:
540     invalidCommandBlock(pRI);
541     return;
542 }
543
544
545 /**
546  * Callee expects const RIL_SMS_WriteArgs *
547  * Payload is:
548  *   int32_t status
549  *   String pdu
550  */
551 static void
552 dispatchSmsWrite (Parcel &p, RequestInfo *pRI) {
553     RIL_SMS_WriteArgs args;
554     int32_t t;
555     status_t status;
556
557     memset (&args, 0, sizeof(args));
558
559     status = p.readInt32(&t);
560     args.status = (int)t;
561
562     args.pdu = strdupReadString(p);
563
564     if (status != NO_ERROR || args.pdu == NULL) {
565         goto invalid;
566     }
567
568     args.smsc = strdupReadString(p);
569
570     startRequest;
571     appendPrintBuf("%s%d,%s,smsc=%s", printBuf, args.status,
572         (char*)args.pdu,  (char*)args.smsc);
573     closeRequest;
574     printRequest(pRI->token, pRI->pCI->requestNumber);
575
576     s_callbacks.onRequest(pRI->pCI->requestNumber, &args, sizeof(args), pRI);
577
578 #ifdef MEMSET_FREED
579     memsetString (args.pdu);
580 #endif
581
582     free (args.pdu);
583
584 #ifdef MEMSET_FREED
585     memset(&args, 0, sizeof(args));
586 #endif
587
588     return;
589 invalid:
590     invalidCommandBlock(pRI);
591     return;
592 }
593
594 /**
595  * Callee expects const RIL_Dial *
596  * Payload is:
597  *   String address
598  *   int32_t clir
599  */
600 static void
601 dispatchDial (Parcel &p, RequestInfo *pRI) {
602     RIL_Dial dial;
603     RIL_UUS_Info uusInfo;
604     int32_t sizeOfDial;
605     int32_t t;
606     int32_t uusPresent;
607     status_t status;
608
609     memset (&dial, 0, sizeof(dial));
610
611     dial.address = strdupReadString(p);
612
613     status = p.readInt32(&t);
614     dial.clir = (int)t;
615
616     if (status != NO_ERROR || dial.address == NULL) {
617         goto invalid;
618     }
619
620     if (s_callbacks.version < 3) { // Remove when partners upgrade to version 3
621         uusPresent = 0;
622         sizeOfDial = sizeof(dial) - sizeof(RIL_UUS_Info *);
623     } else {
624         status = p.readInt32(&uusPresent);
625
626         if (status != NO_ERROR) {
627             goto invalid;
628         }
629
630         if (uusPresent == 0) {
631             dial.uusInfo = NULL;
632         } else {
633             int32_t len;
634
635             memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
636
637             status = p.readInt32(&t);
638             uusInfo.uusType = (RIL_UUS_Type) t;
639
640             status = p.readInt32(&t);
641             uusInfo.uusDcs = (RIL_UUS_DCS) t;
642
643             status = p.readInt32(&len);
644             if (status != NO_ERROR) {
645                 goto invalid;
646             }
647
648             // The java code writes -1 for null arrays
649             if (((int) len) == -1) {
650                 uusInfo.uusData = NULL;
651                 len = 0;
652             } else {
653                 uusInfo.uusData = (char*) p.readInplace(len);
654             }
655
656             uusInfo.uusLength = len;
657             dial.uusInfo = &uusInfo;
658         }
659         sizeOfDial = sizeof(dial);
660     }
661
662     startRequest;
663     appendPrintBuf("%snum=%s,clir=%d", printBuf, dial.address, dial.clir);
664     if (uusPresent) {
665         appendPrintBuf("%s,uusType=%d,uusDcs=%d,uusLen=%d", printBuf,
666                 dial.uusInfo->uusType, dial.uusInfo->uusDcs,
667                 dial.uusInfo->uusLength);
668     }
669     closeRequest;
670     printRequest(pRI->token, pRI->pCI->requestNumber);
671
672     s_callbacks.onRequest(pRI->pCI->requestNumber, &dial, sizeOfDial, pRI);
673
674 #ifdef MEMSET_FREED
675     memsetString (dial.address);
676 #endif
677
678     free (dial.address);
679
680 #ifdef MEMSET_FREED
681     memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
682     memset(&dial, 0, sizeof(dial));
683 #endif
684
685     return;
686 invalid:
687     invalidCommandBlock(pRI);
688     return;
689 }
690
691 /**
692  * Callee expects const RIL_SIM_IO *
693  * Payload is:
694  *   int32_t command
695  *   int32_t fileid
696  *   String path
697  *   int32_t p1, p2, p3
698  *   String data
699  *   String pin2
700  *   String aidPtr
701  */
702 static void
703 dispatchSIM_IO (Parcel &p, RequestInfo *pRI) {
704     union RIL_SIM_IO {
705         RIL_SIM_IO_v6 v6;
706         RIL_SIM_IO_v5 v5;
707     } simIO;
708
709     int32_t t;
710     int size;
711     status_t status;
712
713     memset (&simIO, 0, sizeof(simIO));
714
715     // note we only check status at the end
716
717     status = p.readInt32(&t);
718     simIO.v6.command = (int)t;
719
720     status = p.readInt32(&t);
721     simIO.v6.fileid = (int)t;
722
723     simIO.v6.path = strdupReadString(p);
724
725     status = p.readInt32(&t);
726     simIO.v6.p1 = (int)t;
727
728     status = p.readInt32(&t);
729     simIO.v6.p2 = (int)t;
730
731     status = p.readInt32(&t);
732     simIO.v6.p3 = (int)t;
733
734     simIO.v6.data = strdupReadString(p);
735     simIO.v6.pin2 = strdupReadString(p);
736     simIO.v6.aidPtr = strdupReadString(p);
737
738     startRequest;
739     appendPrintBuf("%scmd=0x%X,efid=0x%X,path=%s,%d,%d,%d,%s,pin2=%s,aid=%s", printBuf,
740         simIO.v6.command, simIO.v6.fileid, (char*)simIO.v6.path,
741         simIO.v6.p1, simIO.v6.p2, simIO.v6.p3,
742         (char*)simIO.v6.data,  (char*)simIO.v6.pin2, simIO.v6.aidPtr);
743     closeRequest;
744     printRequest(pRI->token, pRI->pCI->requestNumber);
745
746     if (status != NO_ERROR) {
747         goto invalid;
748     }
749
750     size = (s_callbacks.version < 6) ? sizeof(simIO.v5) : sizeof(simIO.v6);
751     s_callbacks.onRequest(pRI->pCI->requestNumber, &simIO, size, pRI);
752
753 #ifdef MEMSET_FREED
754     memsetString (simIO.v6.path);
755     memsetString (simIO.v6.data);
756     memsetString (simIO.v6.pin2);
757     memsetString (simIO.v6.aidPtr);
758 #endif
759
760     free (simIO.v6.path);
761     free (simIO.v6.data);
762     free (simIO.v6.pin2);
763     free (simIO.v6.aidPtr);
764
765 #ifdef MEMSET_FREED
766     memset(&simIO, 0, sizeof(simIO));
767 #endif
768
769     return;
770 invalid:
771     invalidCommandBlock(pRI);
772     return;
773 }
774
775 /**
776  * Callee expects const RIL_CallForwardInfo *
777  * Payload is:
778  *  int32_t status/action
779  *  int32_t reason
780  *  int32_t serviceCode
781  *  int32_t toa
782  *  String number  (0 length -> null)
783  *  int32_t timeSeconds
784  */
785 static void
786 dispatchCallForward(Parcel &p, RequestInfo *pRI) {
787     RIL_CallForwardInfo cff;
788     int32_t t;
789     status_t status;
790
791     memset (&cff, 0, sizeof(cff));
792
793     // note we only check status at the end
794
795     status = p.readInt32(&t);
796     cff.status = (int)t;
797
798     status = p.readInt32(&t);
799     cff.reason = (int)t;
800
801     status = p.readInt32(&t);
802     cff.serviceClass = (int)t;
803
804     status = p.readInt32(&t);
805     cff.toa = (int)t;
806
807     cff.number = strdupReadString(p);
808
809     status = p.readInt32(&t);
810     cff.timeSeconds = (int)t;
811
812     if (status != NO_ERROR) {
813         goto invalid;
814     }
815
816     // special case: number 0-length fields is null
817
818     if (cff.number != NULL && strlen (cff.number) == 0) {
819         cff.number = NULL;
820     }
821
822     startRequest;
823     appendPrintBuf("%sstat=%d,reason=%d,serv=%d,toa=%d,%s,tout=%d", printBuf,
824         cff.status, cff.reason, cff.serviceClass, cff.toa,
825         (char*)cff.number, cff.timeSeconds);
826     closeRequest;
827     printRequest(pRI->token, pRI->pCI->requestNumber);
828
829     s_callbacks.onRequest(pRI->pCI->requestNumber, &cff, sizeof(cff), pRI);
830
831 #ifdef MEMSET_FREED
832     memsetString(cff.number);
833 #endif
834
835     free (cff.number);
836
837 #ifdef MEMSET_FREED
838     memset(&cff, 0, sizeof(cff));
839 #endif
840
841     return;
842 invalid:
843     invalidCommandBlock(pRI);
844     return;
845 }
846
847
848 static void
849 dispatchRaw(Parcel &p, RequestInfo *pRI) {
850     int32_t len;
851     status_t status;
852     const void *data;
853
854     status = p.readInt32(&len);
855
856     if (status != NO_ERROR) {
857         goto invalid;
858     }
859
860     // The java code writes -1 for null arrays
861     if (((int)len) == -1) {
862         data = NULL;
863         len = 0;
864     }
865
866     data = p.readInplace(len);
867
868     startRequest;
869     appendPrintBuf("%sraw_size=%d", printBuf, len);
870     closeRequest;
871     printRequest(pRI->token, pRI->pCI->requestNumber);
872
873     s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<void *>(data), len, pRI);
874
875     return;
876 invalid:
877     invalidCommandBlock(pRI);
878     return;
879 }
880
881 static void
882 dispatchCdmaSms(Parcel &p, RequestInfo *pRI) {
883     RIL_CDMA_SMS_Message rcsm;
884     int32_t  t;
885     uint8_t ut;
886     status_t status;
887     int32_t digitCount;
888     int digitLimit;
889
890     memset(&rcsm, 0, sizeof(rcsm));
891
892     status = p.readInt32(&t);
893     rcsm.uTeleserviceID = (int) t;
894
895     status = p.read(&ut,sizeof(ut));
896     rcsm.bIsServicePresent = (uint8_t) ut;
897
898     status = p.readInt32(&t);
899     rcsm.uServicecategory = (int) t;
900
901     status = p.readInt32(&t);
902     rcsm.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
903
904     status = p.readInt32(&t);
905     rcsm.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
906
907     status = p.readInt32(&t);
908     rcsm.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
909
910     status = p.readInt32(&t);
911     rcsm.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
912
913     status = p.read(&ut,sizeof(ut));
914     rcsm.sAddress.number_of_digits= (uint8_t) ut;
915
916     digitLimit= MIN((rcsm.sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
917     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
918         status = p.read(&ut,sizeof(ut));
919         rcsm.sAddress.digits[digitCount] = (uint8_t) ut;
920     }
921
922     status = p.readInt32(&t);
923     rcsm.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
924
925     status = p.read(&ut,sizeof(ut));
926     rcsm.sSubAddress.odd = (uint8_t) ut;
927
928     status = p.read(&ut,sizeof(ut));
929     rcsm.sSubAddress.number_of_digits = (uint8_t) ut;
930
931     digitLimit= MIN((rcsm.sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
932     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
933         status = p.read(&ut,sizeof(ut));
934         rcsm.sSubAddress.digits[digitCount] = (uint8_t) ut;
935     }
936
937     status = p.readInt32(&t);
938     rcsm.uBearerDataLen = (int) t;
939
940     digitLimit= MIN((rcsm.uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
941     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
942         status = p.read(&ut, sizeof(ut));
943         rcsm.aBearerData[digitCount] = (uint8_t) ut;
944     }
945
946     if (status != NO_ERROR) {
947         goto invalid;
948     }
949
950     startRequest;
951     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
952             sAddress.digit_mode=%d, sAddress.Number_mode=%d, sAddress.number_type=%d, ",
953             printBuf, rcsm.uTeleserviceID,rcsm.bIsServicePresent,rcsm.uServicecategory,
954             rcsm.sAddress.digit_mode, rcsm.sAddress.number_mode,rcsm.sAddress.number_type);
955     closeRequest;
956
957     printRequest(pRI->token, pRI->pCI->requestNumber);
958
959     s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsm, sizeof(rcsm),pRI);
960
961 #ifdef MEMSET_FREED
962     memset(&rcsm, 0, sizeof(rcsm));
963 #endif
964
965     return;
966
967 invalid:
968     invalidCommandBlock(pRI);
969     return;
970 }
971
972 static void
973 dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI) {
974     RIL_CDMA_SMS_Ack rcsa;
975     int32_t  t;
976     status_t status;
977     int32_t digitCount;
978
979     memset(&rcsa, 0, sizeof(rcsa));
980
981     status = p.readInt32(&t);
982     rcsa.uErrorClass = (RIL_CDMA_SMS_ErrorClass) t;
983
984     status = p.readInt32(&t);
985     rcsa.uSMSCauseCode = (int) t;
986
987     if (status != NO_ERROR) {
988         goto invalid;
989     }
990
991     startRequest;
992     appendPrintBuf("%suErrorClass=%d, uTLStatus=%d, ",
993             printBuf, rcsa.uErrorClass, rcsa.uSMSCauseCode);
994     closeRequest;
995
996     printRequest(pRI->token, pRI->pCI->requestNumber);
997
998     s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsa, sizeof(rcsa),pRI);
999
1000 #ifdef MEMSET_FREED
1001     memset(&rcsa, 0, sizeof(rcsa));
1002 #endif
1003
1004     return;
1005
1006 invalid:
1007     invalidCommandBlock(pRI);
1008     return;
1009 }
1010
1011 static void
1012 dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI) {
1013     int32_t t;
1014     status_t status;
1015     int32_t num;
1016
1017     status = p.readInt32(&num);
1018     if (status != NO_ERROR) {
1019         goto invalid;
1020     }
1021
1022     {
1023         RIL_GSM_BroadcastSmsConfigInfo gsmBci[num];
1024         RIL_GSM_BroadcastSmsConfigInfo *gsmBciPtrs[num];
1025
1026         startRequest;
1027         for (int i = 0 ; i < num ; i++ ) {
1028             gsmBciPtrs[i] = &gsmBci[i];
1029
1030             status = p.readInt32(&t);
1031             gsmBci[i].fromServiceId = (int) t;
1032
1033             status = p.readInt32(&t);
1034             gsmBci[i].toServiceId = (int) t;
1035
1036             status = p.readInt32(&t);
1037             gsmBci[i].fromCodeScheme = (int) t;
1038
1039             status = p.readInt32(&t);
1040             gsmBci[i].toCodeScheme = (int) t;
1041
1042             status = p.readInt32(&t);
1043             gsmBci[i].selected = (uint8_t) t;
1044
1045             appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId =%d, \
1046                   fromCodeScheme=%d, toCodeScheme=%d, selected =%d]", printBuf, i,
1047                   gsmBci[i].fromServiceId, gsmBci[i].toServiceId,
1048                   gsmBci[i].fromCodeScheme, gsmBci[i].toCodeScheme,
1049                   gsmBci[i].selected);
1050         }
1051         closeRequest;
1052
1053         if (status != NO_ERROR) {
1054             goto invalid;
1055         }
1056
1057         s_callbacks.onRequest(pRI->pCI->requestNumber,
1058                               gsmBciPtrs,
1059                               num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *),
1060                               pRI);
1061
1062 #ifdef MEMSET_FREED
1063         memset(gsmBci, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo));
1064         memset(gsmBciPtrs, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
1065 #endif
1066     }
1067
1068     return;
1069
1070 invalid:
1071     invalidCommandBlock(pRI);
1072     return;
1073 }
1074
1075 static void
1076 dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI) {
1077     int32_t t;
1078     status_t status;
1079     int32_t num;
1080
1081     status = p.readInt32(&num);
1082     if (status != NO_ERROR) {
1083         goto invalid;
1084     }
1085
1086     {
1087         RIL_CDMA_BroadcastSmsConfigInfo cdmaBci[num];
1088         RIL_CDMA_BroadcastSmsConfigInfo *cdmaBciPtrs[num];
1089
1090         startRequest;
1091         for (int i = 0 ; i < num ; i++ ) {
1092             cdmaBciPtrs[i] = &cdmaBci[i];
1093
1094             status = p.readInt32(&t);
1095             cdmaBci[i].service_category = (int) t;
1096
1097             status = p.readInt32(&t);
1098             cdmaBci[i].language = (int) t;
1099
1100             status = p.readInt32(&t);
1101             cdmaBci[i].selected = (uint8_t) t;
1102
1103             appendPrintBuf("%s [%d: service_category=%d, language =%d, \
1104                   entries.bSelected =%d]", printBuf, i, cdmaBci[i].service_category,
1105                   cdmaBci[i].language, cdmaBci[i].selected);
1106         }
1107         closeRequest;
1108
1109         if (status != NO_ERROR) {
1110             goto invalid;
1111         }
1112
1113         s_callbacks.onRequest(pRI->pCI->requestNumber,
1114                               cdmaBciPtrs,
1115                               num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *),
1116                               pRI);
1117
1118 #ifdef MEMSET_FREED
1119         memset(cdmaBci, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo));
1120         memset(cdmaBciPtrs, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *));
1121 #endif
1122     }
1123
1124     return;
1125
1126 invalid:
1127     invalidCommandBlock(pRI);
1128     return;
1129 }
1130
1131 static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI) {
1132     RIL_CDMA_SMS_WriteArgs rcsw;
1133     int32_t  t;
1134     uint32_t ut;
1135     uint8_t  uct;
1136     status_t status;
1137     int32_t  digitCount;
1138
1139     memset(&rcsw, 0, sizeof(rcsw));
1140
1141     status = p.readInt32(&t);
1142     rcsw.status = t;
1143
1144     status = p.readInt32(&t);
1145     rcsw.message.uTeleserviceID = (int) t;
1146
1147     status = p.read(&uct,sizeof(uct));
1148     rcsw.message.bIsServicePresent = (uint8_t) uct;
1149
1150     status = p.readInt32(&t);
1151     rcsw.message.uServicecategory = (int) t;
1152
1153     status = p.readInt32(&t);
1154     rcsw.message.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
1155
1156     status = p.readInt32(&t);
1157     rcsw.message.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
1158
1159     status = p.readInt32(&t);
1160     rcsw.message.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
1161
1162     status = p.readInt32(&t);
1163     rcsw.message.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
1164
1165     status = p.read(&uct,sizeof(uct));
1166     rcsw.message.sAddress.number_of_digits = (uint8_t) uct;
1167
1168     for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_ADDRESS_MAX; digitCount ++) {
1169         status = p.read(&uct,sizeof(uct));
1170         rcsw.message.sAddress.digits[digitCount] = (uint8_t) uct;
1171     }
1172
1173     status = p.readInt32(&t);
1174     rcsw.message.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
1175
1176     status = p.read(&uct,sizeof(uct));
1177     rcsw.message.sSubAddress.odd = (uint8_t) uct;
1178
1179     status = p.read(&uct,sizeof(uct));
1180     rcsw.message.sSubAddress.number_of_digits = (uint8_t) uct;
1181
1182     for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_SUBADDRESS_MAX; digitCount ++) {
1183         status = p.read(&uct,sizeof(uct));
1184         rcsw.message.sSubAddress.digits[digitCount] = (uint8_t) uct;
1185     }
1186
1187     status = p.readInt32(&t);
1188     rcsw.message.uBearerDataLen = (int) t;
1189
1190     for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_BEARER_DATA_MAX; digitCount ++) {
1191         status = p.read(&uct, sizeof(uct));
1192         rcsw.message.aBearerData[digitCount] = (uint8_t) uct;
1193     }
1194
1195     if (status != NO_ERROR) {
1196         goto invalid;
1197     }
1198
1199     startRequest;
1200     appendPrintBuf("%sstatus=%d, message.uTeleserviceID=%d, message.bIsServicePresent=%d, \
1201             message.uServicecategory=%d, message.sAddress.digit_mode=%d, \
1202             message.sAddress.number_mode=%d, \
1203             message.sAddress.number_type=%d, ",
1204             printBuf, rcsw.status, rcsw.message.uTeleserviceID, rcsw.message.bIsServicePresent,
1205             rcsw.message.uServicecategory, rcsw.message.sAddress.digit_mode,
1206             rcsw.message.sAddress.number_mode,
1207             rcsw.message.sAddress.number_type);
1208     closeRequest;
1209
1210     printRequest(pRI->token, pRI->pCI->requestNumber);
1211
1212     s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsw, sizeof(rcsw),pRI);
1213
1214 #ifdef MEMSET_FREED
1215     memset(&rcsw, 0, sizeof(rcsw));
1216 #endif
1217
1218     return;
1219
1220 invalid:
1221     invalidCommandBlock(pRI);
1222     return;
1223
1224 }
1225
1226 // For backwards compatibility in RIL_REQUEST_SETUP_DATA_CALL.
1227 // Version 4 of the RIL interface adds a new PDP type parameter to support
1228 // IPv6 and dual-stack PDP contexts. When dealing with a previous version of
1229 // RIL, remove the parameter from the request.
1230 static void dispatchDataCall(Parcel& p, RequestInfo *pRI) {
1231     // In RIL v3, REQUEST_SETUP_DATA_CALL takes 6 parameters.
1232     const int numParamsRilV3 = 6;
1233
1234     // The first bytes of the RIL parcel contain the request number and the
1235     // serial number - see processCommandBuffer(). Copy them over too.
1236     int pos = p.dataPosition();
1237
1238     int numParams = p.readInt32();
1239     if (s_callbacks.version < 4 && numParams > numParamsRilV3) {
1240       Parcel p2;
1241       p2.appendFrom(&p, 0, pos);
1242       p2.writeInt32(numParamsRilV3);
1243       for(int i = 0; i < numParamsRilV3; i++) {
1244         p2.writeString16(p.readString16());
1245       }
1246       p2.setDataPosition(pos);
1247       dispatchStrings(p2, pRI);
1248     } else {
1249       p.setDataPosition(pos);
1250       dispatchStrings(p, pRI);
1251     }
1252 }
1253
1254 // For backwards compatibility with RILs that dont support RIL_REQUEST_VOICE_RADIO_TECH.
1255 // When all RILs handle this request, this function can be removed and
1256 // the request can be sent directly to the RIL using dispatchVoid.
1257 static void dispatchVoiceRadioTech(Parcel& p, RequestInfo *pRI) {
1258     RIL_RadioState state = s_callbacks.onStateRequest();
1259
1260     if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
1261         RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
1262     }
1263
1264     // RILs that support RADIO_STATE_ON should support this request.
1265     if (RADIO_STATE_ON == state) {
1266         dispatchVoid(p, pRI);
1267         return;
1268     }
1269
1270     // For Older RILs, that do not support RADIO_STATE_ON, assume that they
1271     // will not support this new request either and decode Voice Radio Technology
1272     // from Radio State
1273     voiceRadioTech = decodeVoiceRadioTechnology(state);
1274
1275     if (voiceRadioTech < 0)
1276         RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
1277     else
1278         RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &voiceRadioTech, sizeof(int));
1279 }
1280
1281 // For backwards compatibility in RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:.
1282 // When all RILs handle this request, this function can be removed and
1283 // the request can be sent directly to the RIL using dispatchVoid.
1284 static void dispatchCdmaSubscriptionSource(Parcel& p, RequestInfo *pRI) {
1285     RIL_RadioState state = s_callbacks.onStateRequest();
1286
1287     if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
1288         RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
1289     }
1290
1291     // RILs that support RADIO_STATE_ON should support this request.
1292     if (RADIO_STATE_ON == state) {
1293         dispatchVoid(p, pRI);
1294         return;
1295     }
1296
1297     // For Older RILs, that do not support RADIO_STATE_ON, assume that they
1298     // will not support this new request either and decode CDMA Subscription Source
1299     // from Radio State
1300     cdmaSubscriptionSource = decodeCdmaSubscriptionSource(state);
1301
1302     if (cdmaSubscriptionSource < 0)
1303         RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
1304     else
1305         RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &cdmaSubscriptionSource, sizeof(int));
1306 }
1307
1308 static int
1309 blockingWrite(int fd, const void *buffer, size_t len) {
1310     size_t writeOffset = 0;
1311     const uint8_t *toWrite;
1312
1313     toWrite = (const uint8_t *)buffer;
1314
1315     while (writeOffset < len) {
1316         ssize_t written;
1317         do {
1318             written = write (fd, toWrite + writeOffset,
1319                                 len - writeOffset);
1320         } while (written < 0 && ((errno == EINTR) || (errno == EAGAIN)));
1321
1322         if (written >= 0) {
1323             writeOffset += written;
1324         } else {   // written < 0
1325             RLOGE ("RIL Response: unexpected error on write errno:%d", errno);
1326             close(fd);
1327             return -1;
1328         }
1329     }
1330
1331     return 0;
1332 }
1333
1334 static int
1335 sendResponseRaw (const void *data, size_t dataSize) {
1336     int fd = s_fdCommand;
1337     int ret;
1338     uint32_t header;
1339
1340     if (s_fdCommand < 0) {
1341         return -1;
1342     }
1343
1344     if (dataSize > MAX_COMMAND_BYTES) {
1345         RLOGE("RIL: packet larger than %u (%u)",
1346                 MAX_COMMAND_BYTES, (unsigned int )dataSize);
1347
1348         return -1;
1349     }
1350
1351     pthread_mutex_lock(&s_writeMutex);
1352
1353     header = htonl(dataSize);
1354
1355     ret = blockingWrite(fd, (void *)&header, sizeof(header));
1356
1357     if (ret < 0) {
1358         pthread_mutex_unlock(&s_writeMutex);
1359         return ret;
1360     }
1361
1362     ret = blockingWrite(fd, data, dataSize);
1363
1364     if (ret < 0) {
1365         pthread_mutex_unlock(&s_writeMutex);
1366         return ret;
1367     }
1368
1369     pthread_mutex_unlock(&s_writeMutex);
1370
1371     return 0;
1372 }
1373
1374 static int
1375 sendResponse (Parcel &p) {
1376     printResponse;
1377     return sendResponseRaw(p.data(), p.dataSize());
1378 }
1379
1380 /** response is an int* pointing to an array of ints*/
1381
1382 static int
1383 responseInts(Parcel &p, void *response, size_t responselen) {
1384     int numInts;
1385
1386     if (response == NULL && responselen != 0) {
1387         RLOGE("invalid response: NULL");
1388         return RIL_ERRNO_INVALID_RESPONSE;
1389     }
1390     if (responselen % sizeof(int) != 0) {
1391         RLOGE("invalid response length %d expected multiple of %d\n",
1392             (int)responselen, (int)sizeof(int));
1393         return RIL_ERRNO_INVALID_RESPONSE;
1394     }
1395
1396     int *p_int = (int *) response;
1397
1398     numInts = responselen / sizeof(int *);
1399     p.writeInt32 (numInts);
1400
1401     /* each int*/
1402     startResponse;
1403     for (int i = 0 ; i < numInts ; i++) {
1404         appendPrintBuf("%s%d,", printBuf, p_int[i]);
1405         p.writeInt32(p_int[i]);
1406     }
1407     removeLastChar;
1408     closeResponse;
1409
1410     return 0;
1411 }
1412
1413 /** response is a char **, pointing to an array of char *'s
1414     The parcel will begin with the version */
1415 static int responseStringsWithVersion(int version, Parcel &p, void *response, size_t responselen) {
1416     p.writeInt32(version);
1417     return responseStrings(p, response, responselen);
1418 }
1419
1420 /** response is a char **, pointing to an array of char *'s */
1421 static int responseStrings(Parcel &p, void *response, size_t responselen) {
1422     int numStrings;
1423
1424     if (response == NULL && responselen != 0) {
1425         RLOGE("invalid response: NULL");
1426         return RIL_ERRNO_INVALID_RESPONSE;
1427     }
1428     if (responselen % sizeof(char *) != 0) {
1429         RLOGE("invalid response length %d expected multiple of %d\n",
1430             (int)responselen, (int)sizeof(char *));
1431         return RIL_ERRNO_INVALID_RESPONSE;
1432     }
1433
1434     if (response == NULL) {
1435         p.writeInt32 (0);
1436     } else {
1437         char **p_cur = (char **) response;
1438
1439         numStrings = responselen / sizeof(char *);
1440         p.writeInt32 (numStrings);
1441
1442         /* each string*/
1443         startResponse;
1444         for (int i = 0 ; i < numStrings ; i++) {
1445             appendPrintBuf("%s%s,", printBuf, (char*)p_cur[i]);
1446             writeStringToParcel (p, p_cur[i]);
1447         }
1448         removeLastChar;
1449         closeResponse;
1450     }
1451     return 0;
1452 }
1453
1454
1455 /**
1456  * NULL strings are accepted
1457  * FIXME currently ignores responselen
1458  */
1459 static int responseString(Parcel &p, void *response, size_t responselen) {
1460     /* one string only */
1461     startResponse;
1462     appendPrintBuf("%s%s", printBuf, (char*)response);
1463     closeResponse;
1464
1465     writeStringToParcel(p, (const char *)response);
1466
1467     return 0;
1468 }
1469
1470 static int responseVoid(Parcel &p, void *response, size_t responselen) {
1471     startResponse;
1472     removeLastChar;
1473     return 0;
1474 }
1475
1476 static int responseCallList(Parcel &p, void *response, size_t responselen) {
1477     int num;
1478
1479     if (response == NULL && responselen != 0) {
1480         RLOGE("invalid response: NULL");
1481         return RIL_ERRNO_INVALID_RESPONSE;
1482     }
1483
1484     if (responselen % sizeof (RIL_Call *) != 0) {
1485         RLOGE("invalid response length %d expected multiple of %d\n",
1486             (int)responselen, (int)sizeof (RIL_Call *));
1487         return RIL_ERRNO_INVALID_RESPONSE;
1488     }
1489
1490     startResponse;
1491     /* number of call info's */
1492     num = responselen / sizeof(RIL_Call *);
1493     p.writeInt32(num);
1494
1495     for (int i = 0 ; i < num ; i++) {
1496         RIL_Call *p_cur = ((RIL_Call **) response)[i];
1497         /* each call info */
1498         p.writeInt32(p_cur->state);
1499         p.writeInt32(p_cur->index);
1500         p.writeInt32(p_cur->toa);
1501         p.writeInt32(p_cur->isMpty);
1502         p.writeInt32(p_cur->isMT);
1503         p.writeInt32(p_cur->als);
1504         p.writeInt32(p_cur->isVoice);
1505         p.writeInt32(p_cur->isVoicePrivacy);
1506         writeStringToParcel(p, p_cur->number);
1507         p.writeInt32(p_cur->numberPresentation);
1508         writeStringToParcel(p, p_cur->name);
1509         p.writeInt32(p_cur->namePresentation);
1510         // Remove when partners upgrade to version 3
1511         if ((s_callbacks.version < 3) || (p_cur->uusInfo == NULL || p_cur->uusInfo->uusData == NULL)) {
1512             p.writeInt32(0); /* UUS Information is absent */
1513         } else {
1514             RIL_UUS_Info *uusInfo = p_cur->uusInfo;
1515             p.writeInt32(1); /* UUS Information is present */
1516             p.writeInt32(uusInfo->uusType);
1517             p.writeInt32(uusInfo->uusDcs);
1518             p.writeInt32(uusInfo->uusLength);
1519             p.write(uusInfo->uusData, uusInfo->uusLength);
1520         }
1521         appendPrintBuf("%s[id=%d,%s,toa=%d,",
1522             printBuf,
1523             p_cur->index,
1524             callStateToString(p_cur->state),
1525             p_cur->toa);
1526         appendPrintBuf("%s%s,%s,als=%d,%s,%s,",
1527             printBuf,
1528             (p_cur->isMpty)?"conf":"norm",
1529             (p_cur->isMT)?"mt":"mo",
1530             p_cur->als,
1531             (p_cur->isVoice)?"voc":"nonvoc",
1532             (p_cur->isVoicePrivacy)?"evp":"noevp");
1533         appendPrintBuf("%s%s,cli=%d,name='%s',%d]",
1534             printBuf,
1535             p_cur->number,
1536             p_cur->numberPresentation,
1537             p_cur->name,
1538             p_cur->namePresentation);
1539     }
1540     removeLastChar;
1541     closeResponse;
1542
1543     return 0;
1544 }
1545
1546 static int responseSMS(Parcel &p, void *response, size_t responselen) {
1547     if (response == NULL) {
1548         RLOGE("invalid response: NULL");
1549         return RIL_ERRNO_INVALID_RESPONSE;
1550     }
1551
1552     if (responselen != sizeof (RIL_SMS_Response) ) {
1553         RLOGE("invalid response length %d expected %d",
1554                 (int)responselen, (int)sizeof (RIL_SMS_Response));
1555         return RIL_ERRNO_INVALID_RESPONSE;
1556     }
1557
1558     RIL_SMS_Response *p_cur = (RIL_SMS_Response *) response;
1559
1560     p.writeInt32(p_cur->messageRef);
1561     writeStringToParcel(p, p_cur->ackPDU);
1562     p.writeInt32(p_cur->errorCode);
1563
1564     startResponse;
1565     appendPrintBuf("%s%d,%s,%d", printBuf, p_cur->messageRef,
1566         (char*)p_cur->ackPDU, p_cur->errorCode);
1567     closeResponse;
1568
1569     return 0;
1570 }
1571
1572 static int responseDataCallListV4(Parcel &p, void *response, size_t responselen)
1573 {
1574     if (response == NULL && responselen != 0) {
1575         RLOGE("invalid response: NULL");
1576         return RIL_ERRNO_INVALID_RESPONSE;
1577     }
1578
1579     if (responselen % sizeof(RIL_Data_Call_Response_v4) != 0) {
1580         RLOGE("invalid response length %d expected multiple of %d",
1581                 (int)responselen, (int)sizeof(RIL_Data_Call_Response_v4));
1582         return RIL_ERRNO_INVALID_RESPONSE;
1583     }
1584
1585     int num = responselen / sizeof(RIL_Data_Call_Response_v4);
1586     p.writeInt32(num);
1587
1588     RIL_Data_Call_Response_v4 *p_cur = (RIL_Data_Call_Response_v4 *) response;
1589     startResponse;
1590     int i;
1591     for (i = 0; i < num; i++) {
1592         p.writeInt32(p_cur[i].cid);
1593         p.writeInt32(p_cur[i].active);
1594         writeStringToParcel(p, p_cur[i].type);
1595         // apn is not used, so don't send.
1596         writeStringToParcel(p, p_cur[i].address);
1597         appendPrintBuf("%s[cid=%d,%s,%s,%s],", printBuf,
1598             p_cur[i].cid,
1599             (p_cur[i].active==0)?"down":"up",
1600             (char*)p_cur[i].type,
1601             (char*)p_cur[i].address);
1602     }
1603     removeLastChar;
1604     closeResponse;
1605
1606     return 0;
1607 }
1608
1609 static int responseDataCallList(Parcel &p, void *response, size_t responselen)
1610 {
1611     // Write version
1612     p.writeInt32(s_callbacks.version);
1613
1614     if (s_callbacks.version < 5) {
1615         return responseDataCallListV4(p, response, responselen);
1616     } else {
1617         if (response == NULL && responselen != 0) {
1618             RLOGE("invalid response: NULL");
1619             return RIL_ERRNO_INVALID_RESPONSE;
1620         }
1621
1622         if (responselen % sizeof(RIL_Data_Call_Response_v6) != 0) {
1623             RLOGE("invalid response length %d expected multiple of %d",
1624                     (int)responselen, (int)sizeof(RIL_Data_Call_Response_v6));
1625             return RIL_ERRNO_INVALID_RESPONSE;
1626         }
1627
1628         int num = responselen / sizeof(RIL_Data_Call_Response_v6);
1629         p.writeInt32(num);
1630
1631         RIL_Data_Call_Response_v6 *p_cur = (RIL_Data_Call_Response_v6 *) response;
1632         startResponse;
1633         int i;
1634         for (i = 0; i < num; i++) {
1635             p.writeInt32((int)p_cur[i].status);
1636             p.writeInt32(p_cur[i].suggestedRetryTime);
1637             p.writeInt32(p_cur[i].cid);
1638             p.writeInt32(p_cur[i].active);
1639             writeStringToParcel(p, p_cur[i].type);
1640             writeStringToParcel(p, p_cur[i].ifname);
1641             writeStringToParcel(p, p_cur[i].addresses);
1642             writeStringToParcel(p, p_cur[i].dnses);
1643             writeStringToParcel(p, p_cur[i].gateways);
1644             appendPrintBuf("%s[status=%d,retry=%d,cid=%d,%s,%s,%s,%s,%s,%s],", printBuf,
1645                 p_cur[i].status,
1646                 p_cur[i].suggestedRetryTime,
1647                 p_cur[i].cid,
1648                 (p_cur[i].active==0)?"down":"up",
1649                 (char*)p_cur[i].type,
1650                 (char*)p_cur[i].ifname,
1651                 (char*)p_cur[i].addresses,
1652                 (char*)p_cur[i].dnses,
1653                 (char*)p_cur[i].gateways);
1654         }
1655         removeLastChar;
1656         closeResponse;
1657     }
1658
1659     return 0;
1660 }
1661
1662 static int responseSetupDataCall(Parcel &p, void *response, size_t responselen)
1663 {
1664     if (s_callbacks.version < 5) {
1665         return responseStringsWithVersion(s_callbacks.version, p, response, responselen);
1666     } else {
1667         return responseDataCallList(p, response, responselen);
1668     }
1669 }
1670
1671 static int responseRaw(Parcel &p, void *response, size_t responselen) {
1672     if (response == NULL && responselen != 0) {
1673         RLOGE("invalid response: NULL with responselen != 0");
1674         return RIL_ERRNO_INVALID_RESPONSE;
1675     }
1676
1677     // The java code reads -1 size as null byte array
1678     if (response == NULL) {
1679         p.writeInt32(-1);
1680     } else {
1681         p.writeInt32(responselen);
1682         p.write(response, responselen);
1683     }
1684
1685     return 0;
1686 }
1687
1688
1689 static int responseSIM_IO(Parcel &p, void *response, size_t responselen) {
1690     if (response == NULL) {
1691         RLOGE("invalid response: NULL");
1692         return RIL_ERRNO_INVALID_RESPONSE;
1693     }
1694
1695     if (responselen != sizeof (RIL_SIM_IO_Response) ) {
1696         RLOGE("invalid response length was %d expected %d",
1697                 (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
1698         return RIL_ERRNO_INVALID_RESPONSE;
1699     }
1700
1701     RIL_SIM_IO_Response *p_cur = (RIL_SIM_IO_Response *) response;
1702     p.writeInt32(p_cur->sw1);
1703     p.writeInt32(p_cur->sw2);
1704     writeStringToParcel(p, p_cur->simResponse);
1705
1706     startResponse;
1707     appendPrintBuf("%ssw1=0x%X,sw2=0x%X,%s", printBuf, p_cur->sw1, p_cur->sw2,
1708         (char*)p_cur->simResponse);
1709     closeResponse;
1710
1711
1712     return 0;
1713 }
1714
1715 static int responseCallForwards(Parcel &p, void *response, size_t responselen) {
1716     int num;
1717
1718     if (response == NULL && responselen != 0) {
1719         RLOGE("invalid response: NULL");
1720         return RIL_ERRNO_INVALID_RESPONSE;
1721     }
1722
1723     if (responselen % sizeof(RIL_CallForwardInfo *) != 0) {
1724         RLOGE("invalid response length %d expected multiple of %d",
1725                 (int)responselen, (int)sizeof(RIL_CallForwardInfo *));
1726         return RIL_ERRNO_INVALID_RESPONSE;
1727     }
1728
1729     /* number of call info's */
1730     num = responselen / sizeof(RIL_CallForwardInfo *);
1731     p.writeInt32(num);
1732
1733     startResponse;
1734     for (int i = 0 ; i < num ; i++) {
1735         RIL_CallForwardInfo *p_cur = ((RIL_CallForwardInfo **) response)[i];
1736
1737         p.writeInt32(p_cur->status);
1738         p.writeInt32(p_cur->reason);
1739         p.writeInt32(p_cur->serviceClass);
1740         p.writeInt32(p_cur->toa);
1741         writeStringToParcel(p, p_cur->number);
1742         p.writeInt32(p_cur->timeSeconds);
1743         appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
1744             (p_cur->status==1)?"enable":"disable",
1745             p_cur->reason, p_cur->serviceClass, p_cur->toa,
1746             (char*)p_cur->number,
1747             p_cur->timeSeconds);
1748     }
1749     removeLastChar;
1750     closeResponse;
1751
1752     return 0;
1753 }
1754
1755 static int responseSsn(Parcel &p, void *response, size_t responselen) {
1756     if (response == NULL) {
1757         RLOGE("invalid response: NULL");
1758         return RIL_ERRNO_INVALID_RESPONSE;
1759     }
1760
1761     if (responselen != sizeof(RIL_SuppSvcNotification)) {
1762         RLOGE("invalid response length was %d expected %d",
1763                 (int)responselen, (int)sizeof (RIL_SuppSvcNotification));
1764         return RIL_ERRNO_INVALID_RESPONSE;
1765     }
1766
1767     RIL_SuppSvcNotification *p_cur = (RIL_SuppSvcNotification *) response;
1768     p.writeInt32(p_cur->notificationType);
1769     p.writeInt32(p_cur->code);
1770     p.writeInt32(p_cur->index);
1771     p.writeInt32(p_cur->type);
1772     writeStringToParcel(p, p_cur->number);
1773
1774     startResponse;
1775     appendPrintBuf("%s%s,code=%d,id=%d,type=%d,%s", printBuf,
1776         (p_cur->notificationType==0)?"mo":"mt",
1777          p_cur->code, p_cur->index, p_cur->type,
1778         (char*)p_cur->number);
1779     closeResponse;
1780
1781     return 0;
1782 }
1783
1784 static int responseCellList(Parcel &p, void *response, size_t responselen) {
1785     int num;
1786
1787     if (response == NULL && responselen != 0) {
1788         RLOGE("invalid response: NULL");
1789         return RIL_ERRNO_INVALID_RESPONSE;
1790     }
1791
1792     if (responselen % sizeof (RIL_NeighboringCell *) != 0) {
1793         RLOGE("invalid response length %d expected multiple of %d\n",
1794             (int)responselen, (int)sizeof (RIL_NeighboringCell *));
1795         return RIL_ERRNO_INVALID_RESPONSE;
1796     }
1797
1798     startResponse;
1799     /* number of records */
1800     num = responselen / sizeof(RIL_NeighboringCell *);
1801     p.writeInt32(num);
1802
1803     for (int i = 0 ; i < num ; i++) {
1804         RIL_NeighboringCell *p_cur = ((RIL_NeighboringCell **) response)[i];
1805
1806         p.writeInt32(p_cur->rssi);
1807         writeStringToParcel (p, p_cur->cid);
1808
1809         appendPrintBuf("%s[cid=%s,rssi=%d],", printBuf,
1810             p_cur->cid, p_cur->rssi);
1811     }
1812     removeLastChar;
1813     closeResponse;
1814
1815     return 0;
1816 }
1817
1818 /**
1819  * Marshall the signalInfoRecord into the parcel if it exists.
1820  */
1821 static void marshallSignalInfoRecord(Parcel &p,
1822             RIL_CDMA_SignalInfoRecord &p_signalInfoRecord) {
1823     p.writeInt32(p_signalInfoRecord.isPresent);
1824     p.writeInt32(p_signalInfoRecord.signalType);
1825     p.writeInt32(p_signalInfoRecord.alertPitch);
1826     p.writeInt32(p_signalInfoRecord.signal);
1827 }
1828
1829 static int responseCdmaInformationRecords(Parcel &p,
1830             void *response, size_t responselen) {
1831     int num;
1832     char* string8 = NULL;
1833     int buffer_lenght;
1834     RIL_CDMA_InformationRecord *infoRec;
1835
1836     if (response == NULL && responselen != 0) {
1837         RLOGE("invalid response: NULL");
1838         return RIL_ERRNO_INVALID_RESPONSE;
1839     }
1840
1841     if (responselen != sizeof (RIL_CDMA_InformationRecords)) {
1842         RLOGE("invalid response length %d expected multiple of %d\n",
1843             (int)responselen, (int)sizeof (RIL_CDMA_InformationRecords *));
1844         return RIL_ERRNO_INVALID_RESPONSE;
1845     }
1846
1847     RIL_CDMA_InformationRecords *p_cur =
1848                              (RIL_CDMA_InformationRecords *) response;
1849     num = MIN(p_cur->numberOfInfoRecs, RIL_CDMA_MAX_NUMBER_OF_INFO_RECS);
1850
1851     startResponse;
1852     p.writeInt32(num);
1853
1854     for (int i = 0 ; i < num ; i++) {
1855         infoRec = &p_cur->infoRec[i];
1856         p.writeInt32(infoRec->name);
1857         switch (infoRec->name) {
1858             case RIL_CDMA_DISPLAY_INFO_REC:
1859             case RIL_CDMA_EXTENDED_DISPLAY_INFO_REC:
1860                 if (infoRec->rec.display.alpha_len >
1861                                          CDMA_ALPHA_INFO_BUFFER_LENGTH) {
1862                     RLOGE("invalid display info response length %d \
1863                           expected not more than %d\n",
1864                          (int)infoRec->rec.display.alpha_len,
1865                          CDMA_ALPHA_INFO_BUFFER_LENGTH);
1866                     return RIL_ERRNO_INVALID_RESPONSE;
1867                 }
1868                 string8 = (char*) malloc((infoRec->rec.display.alpha_len + 1)
1869                                                              * sizeof(char) );
1870                 for (int i = 0 ; i < infoRec->rec.display.alpha_len ; i++) {
1871                     string8[i] = infoRec->rec.display.alpha_buf[i];
1872                 }
1873                 string8[(int)infoRec->rec.display.alpha_len] = '\0';
1874                 writeStringToParcel(p, (const char*)string8);
1875                 free(string8);
1876                 string8 = NULL;
1877                 break;
1878             case RIL_CDMA_CALLED_PARTY_NUMBER_INFO_REC:
1879             case RIL_CDMA_CALLING_PARTY_NUMBER_INFO_REC:
1880             case RIL_CDMA_CONNECTED_NUMBER_INFO_REC:
1881                 if (infoRec->rec.number.len > CDMA_NUMBER_INFO_BUFFER_LENGTH) {
1882                     RLOGE("invalid display info response length %d \
1883                           expected not more than %d\n",
1884                          (int)infoRec->rec.number.len,
1885                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
1886                     return RIL_ERRNO_INVALID_RESPONSE;
1887                 }
1888                 string8 = (char*) malloc((infoRec->rec.number.len + 1)
1889                                                              * sizeof(char) );
1890                 for (int i = 0 ; i < infoRec->rec.number.len; i++) {
1891                     string8[i] = infoRec->rec.number.buf[i];
1892                 }
1893                 string8[(int)infoRec->rec.number.len] = '\0';
1894                 writeStringToParcel(p, (const char*)string8);
1895                 free(string8);
1896                 string8 = NULL;
1897                 p.writeInt32(infoRec->rec.number.number_type);
1898                 p.writeInt32(infoRec->rec.number.number_plan);
1899                 p.writeInt32(infoRec->rec.number.pi);
1900                 p.writeInt32(infoRec->rec.number.si);
1901                 break;
1902             case RIL_CDMA_SIGNAL_INFO_REC:
1903                 p.writeInt32(infoRec->rec.signal.isPresent);
1904                 p.writeInt32(infoRec->rec.signal.signalType);
1905                 p.writeInt32(infoRec->rec.signal.alertPitch);
1906                 p.writeInt32(infoRec->rec.signal.signal);
1907
1908                 appendPrintBuf("%sisPresent=%X, signalType=%X, \
1909                                 alertPitch=%X, signal=%X, ",
1910                    printBuf, (int)infoRec->rec.signal.isPresent,
1911                    (int)infoRec->rec.signal.signalType,
1912                    (int)infoRec->rec.signal.alertPitch,
1913                    (int)infoRec->rec.signal.signal);
1914                 removeLastChar;
1915                 break;
1916             case RIL_CDMA_REDIRECTING_NUMBER_INFO_REC:
1917                 if (infoRec->rec.redir.redirectingNumber.len >
1918                                               CDMA_NUMBER_INFO_BUFFER_LENGTH) {
1919                     RLOGE("invalid display info response length %d \
1920                           expected not more than %d\n",
1921                          (int)infoRec->rec.redir.redirectingNumber.len,
1922                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
1923                     return RIL_ERRNO_INVALID_RESPONSE;
1924                 }
1925                 string8 = (char*) malloc((infoRec->rec.redir.redirectingNumber
1926                                           .len + 1) * sizeof(char) );
1927                 for (int i = 0;
1928                          i < infoRec->rec.redir.redirectingNumber.len;
1929                          i++) {
1930                     string8[i] = infoRec->rec.redir.redirectingNumber.buf[i];
1931                 }
1932                 string8[(int)infoRec->rec.redir.redirectingNumber.len] = '\0';
1933                 writeStringToParcel(p, (const char*)string8);
1934                 free(string8);
1935                 string8 = NULL;
1936                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_type);
1937                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_plan);
1938                 p.writeInt32(infoRec->rec.redir.redirectingNumber.pi);
1939                 p.writeInt32(infoRec->rec.redir.redirectingNumber.si);
1940                 p.writeInt32(infoRec->rec.redir.redirectingReason);
1941                 break;
1942             case RIL_CDMA_LINE_CONTROL_INFO_REC:
1943                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPolarityIncluded);
1944                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlToggle);
1945                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlReverse);
1946                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPowerDenial);
1947
1948                 appendPrintBuf("%slineCtrlPolarityIncluded=%d, \
1949                                 lineCtrlToggle=%d, lineCtrlReverse=%d, \
1950                                 lineCtrlPowerDenial=%d, ", printBuf,
1951                        (int)infoRec->rec.lineCtrl.lineCtrlPolarityIncluded,
1952                        (int)infoRec->rec.lineCtrl.lineCtrlToggle,
1953                        (int)infoRec->rec.lineCtrl.lineCtrlReverse,
1954                        (int)infoRec->rec.lineCtrl.lineCtrlPowerDenial);
1955                 removeLastChar;
1956                 break;
1957             case RIL_CDMA_T53_CLIR_INFO_REC:
1958                 p.writeInt32((int)(infoRec->rec.clir.cause));
1959
1960                 appendPrintBuf("%scause%d", printBuf, infoRec->rec.clir.cause);
1961                 removeLastChar;
1962                 break;
1963             case RIL_CDMA_T53_AUDIO_CONTROL_INFO_REC:
1964                 p.writeInt32(infoRec->rec.audioCtrl.upLink);
1965                 p.writeInt32(infoRec->rec.audioCtrl.downLink);
1966
1967                 appendPrintBuf("%supLink=%d, downLink=%d, ", printBuf,
1968                         infoRec->rec.audioCtrl.upLink,
1969                         infoRec->rec.audioCtrl.downLink);
1970                 removeLastChar;
1971                 break;
1972             case RIL_CDMA_T53_RELEASE_INFO_REC:
1973                 // TODO(Moto): See David Krause, he has the answer:)
1974                 RLOGE("RIL_CDMA_T53_RELEASE_INFO_REC: return INVALID_RESPONSE");
1975                 return RIL_ERRNO_INVALID_RESPONSE;
1976             default:
1977                 RLOGE("Incorrect name value");
1978                 return RIL_ERRNO_INVALID_RESPONSE;
1979         }
1980     }
1981     closeResponse;
1982
1983     return 0;
1984 }
1985
1986 static int responseRilSignalStrength(Parcel &p,
1987                     void *response, size_t responselen) {
1988     if (response == NULL && responselen != 0) {
1989         RLOGE("invalid response: NULL");
1990         return RIL_ERRNO_INVALID_RESPONSE;
1991     }
1992
1993     if (responselen >= sizeof (RIL_SignalStrength_v5)) {
1994         RIL_SignalStrength_v6 *p_cur = ((RIL_SignalStrength_v6 *) response);
1995
1996         p.writeInt32(p_cur->GW_SignalStrength.signalStrength);
1997         p.writeInt32(p_cur->GW_SignalStrength.bitErrorRate);
1998         p.writeInt32(p_cur->CDMA_SignalStrength.dbm);
1999         p.writeInt32(p_cur->CDMA_SignalStrength.ecio);
2000         p.writeInt32(p_cur->EVDO_SignalStrength.dbm);
2001         p.writeInt32(p_cur->EVDO_SignalStrength.ecio);
2002         p.writeInt32(p_cur->EVDO_SignalStrength.signalNoiseRatio);
2003         if (responselen >= sizeof (RIL_SignalStrength_v6)) {
2004             /*
2005              * Fixup LTE for backwards compatibility
2006              */
2007             if (s_callbacks.version <= 6) {
2008                 // signalStrength: -1 -> 99
2009                 if (p_cur->LTE_SignalStrength.signalStrength == -1) {
2010                     p_cur->LTE_SignalStrength.signalStrength = 99;
2011                 }
2012                 // rsrp: -1 -> INT_MAX all other negative value to positive.
2013                 // So remap here
2014                 if (p_cur->LTE_SignalStrength.rsrp == -1) {
2015                     p_cur->LTE_SignalStrength.rsrp = INT_MAX;
2016                 } else if (p_cur->LTE_SignalStrength.rsrp < -1) {
2017                     p_cur->LTE_SignalStrength.rsrp = -p_cur->LTE_SignalStrength.rsrp;
2018                 }
2019                 // rsrq: -1 -> INT_MAX
2020                 if (p_cur->LTE_SignalStrength.rsrq == -1) {
2021                     p_cur->LTE_SignalStrength.rsrq = INT_MAX;
2022                 }
2023                 // Not remapping rssnr is already using INT_MAX
2024
2025                 // cqi: -1 -> INT_MAX
2026                 if (p_cur->LTE_SignalStrength.cqi == -1) {
2027                     p_cur->LTE_SignalStrength.cqi = INT_MAX;
2028                 }
2029             }
2030             p.writeInt32(p_cur->LTE_SignalStrength.signalStrength);
2031             p.writeInt32(p_cur->LTE_SignalStrength.rsrp);
2032             p.writeInt32(p_cur->LTE_SignalStrength.rsrq);
2033             p.writeInt32(p_cur->LTE_SignalStrength.rssnr);
2034             p.writeInt32(p_cur->LTE_SignalStrength.cqi);
2035         } else {
2036             p.writeInt32(99);
2037             p.writeInt32(INT_MAX);
2038             p.writeInt32(INT_MAX);
2039             p.writeInt32(INT_MAX);
2040             p.writeInt32(INT_MAX);
2041         }
2042
2043         startResponse;
2044         appendPrintBuf("%s[signalStrength=%d,bitErrorRate=%d,\
2045                 CDMA_SS.dbm=%d,CDMA_SSecio=%d,\
2046                 EVDO_SS.dbm=%d,EVDO_SS.ecio=%d,\
2047                 EVDO_SS.signalNoiseRatio=%d,\
2048                 LTE_SS.signalStrength=%d,LTE_SS.rsrp=%d,LTE_SS.rsrq=%d,\
2049                 LTE_SS.rssnr=%d,LTE_SS.cqi=%d]",
2050                 printBuf,
2051                 p_cur->GW_SignalStrength.signalStrength,
2052                 p_cur->GW_SignalStrength.bitErrorRate,
2053                 p_cur->CDMA_SignalStrength.dbm,
2054                 p_cur->CDMA_SignalStrength.ecio,
2055                 p_cur->EVDO_SignalStrength.dbm,
2056                 p_cur->EVDO_SignalStrength.ecio,
2057                 p_cur->EVDO_SignalStrength.signalNoiseRatio,
2058                 p_cur->LTE_SignalStrength.signalStrength,
2059                 p_cur->LTE_SignalStrength.rsrp,
2060                 p_cur->LTE_SignalStrength.rsrq,
2061                 p_cur->LTE_SignalStrength.rssnr,
2062                 p_cur->LTE_SignalStrength.cqi);
2063         closeResponse;
2064
2065     } else {
2066         RLOGE("invalid response length");
2067         return RIL_ERRNO_INVALID_RESPONSE;
2068     }
2069
2070     return 0;
2071 }
2072
2073 static int responseCallRing(Parcel &p, void *response, size_t responselen) {
2074     if ((response == NULL) || (responselen == 0)) {
2075         return responseVoid(p, response, responselen);
2076     } else {
2077         return responseCdmaSignalInfoRecord(p, response, responselen);
2078     }
2079 }
2080
2081 static int responseCdmaSignalInfoRecord(Parcel &p, void *response, size_t responselen) {
2082     if (response == NULL || responselen == 0) {
2083         RLOGE("invalid response: NULL");
2084         return RIL_ERRNO_INVALID_RESPONSE;
2085     }
2086
2087     if (responselen != sizeof (RIL_CDMA_SignalInfoRecord)) {
2088         RLOGE("invalid response length %d expected sizeof (RIL_CDMA_SignalInfoRecord) of %d\n",
2089             (int)responselen, (int)sizeof (RIL_CDMA_SignalInfoRecord));
2090         return RIL_ERRNO_INVALID_RESPONSE;
2091     }
2092
2093     startResponse;
2094
2095     RIL_CDMA_SignalInfoRecord *p_cur = ((RIL_CDMA_SignalInfoRecord *) response);
2096     marshallSignalInfoRecord(p, *p_cur);
2097
2098     appendPrintBuf("%s[isPresent=%d,signalType=%d,alertPitch=%d\
2099               signal=%d]",
2100               printBuf,
2101               p_cur->isPresent,
2102               p_cur->signalType,
2103               p_cur->alertPitch,
2104               p_cur->signal);
2105
2106     closeResponse;
2107     return 0;
2108 }
2109
2110 static int responseCdmaCallWaiting(Parcel &p, void *response,
2111             size_t responselen) {
2112     if (response == NULL && responselen != 0) {
2113         RLOGE("invalid response: NULL");
2114         return RIL_ERRNO_INVALID_RESPONSE;
2115     }
2116
2117     if (responselen < sizeof(RIL_CDMA_CallWaiting_v6)) {
2118         RLOGW("Upgrade to ril version %d\n", RIL_VERSION);
2119     }
2120
2121     RIL_CDMA_CallWaiting_v6 *p_cur = ((RIL_CDMA_CallWaiting_v6 *) response);
2122
2123     writeStringToParcel(p, p_cur->number);
2124     p.writeInt32(p_cur->numberPresentation);
2125     writeStringToParcel(p, p_cur->name);
2126     marshallSignalInfoRecord(p, p_cur->signalInfoRecord);
2127
2128     if (responselen >= sizeof(RIL_CDMA_CallWaiting_v6)) {
2129         p.writeInt32(p_cur->number_type);
2130         p.writeInt32(p_cur->number_plan);
2131     } else {
2132         p.writeInt32(0);
2133         p.writeInt32(0);
2134     }
2135
2136     startResponse;
2137     appendPrintBuf("%snumber=%s,numberPresentation=%d, name=%s,\
2138             signalInfoRecord[isPresent=%d,signalType=%d,alertPitch=%d\
2139             signal=%d,number_type=%d,number_plan=%d]",
2140             printBuf,
2141             p_cur->number,
2142             p_cur->numberPresentation,
2143             p_cur->name,
2144             p_cur->signalInfoRecord.isPresent,
2145             p_cur->signalInfoRecord.signalType,
2146             p_cur->signalInfoRecord.alertPitch,
2147             p_cur->signalInfoRecord.signal,
2148             p_cur->number_type,
2149             p_cur->number_plan);
2150     closeResponse;
2151
2152     return 0;
2153 }
2154
2155 static int responseSimRefresh(Parcel &p, void *response, size_t responselen) {
2156     if (response == NULL && responselen != 0) {
2157         RLOGE("responseSimRefresh: invalid response: NULL");
2158         return RIL_ERRNO_INVALID_RESPONSE;
2159     }
2160
2161     startResponse;
2162     if (s_callbacks.version == 7) {
2163         RIL_SimRefreshResponse_v7 *p_cur = ((RIL_SimRefreshResponse_v7 *) response);
2164         p.writeInt32(p_cur->result);
2165         p.writeInt32(p_cur->ef_id);
2166         writeStringToParcel(p, p_cur->aid);
2167
2168         appendPrintBuf("%sresult=%d, ef_id=%d, aid=%s",
2169                 printBuf,
2170                 p_cur->result,
2171                 p_cur->ef_id,
2172                 p_cur->aid);
2173     } else {
2174         int *p_cur = ((int *) response);
2175         p.writeInt32(p_cur[0]);
2176         p.writeInt32(p_cur[1]);
2177         writeStringToParcel(p, NULL);
2178
2179         appendPrintBuf("%sresult=%d, ef_id=%d",
2180                 printBuf,
2181                 p_cur[0],
2182                 p_cur[1]);
2183     }
2184     closeResponse;
2185
2186     return 0;
2187 }
2188
2189 static int responseCellInfoList(Parcel &p, void *response, size_t responselen)
2190 {
2191     if (response == NULL && responselen != 0) {
2192         RLOGE("invalid response: NULL");
2193         return RIL_ERRNO_INVALID_RESPONSE;
2194     }
2195
2196     if (responselen % sizeof(RIL_CellInfo) != 0) {
2197         RLOGE("invalid response length %d expected multiple of %d",
2198                 (int)responselen, (int)sizeof(RIL_CellInfo));
2199         return RIL_ERRNO_INVALID_RESPONSE;
2200     }
2201
2202     int num = responselen / sizeof(RIL_CellInfo);
2203     p.writeInt32(num);
2204
2205     RIL_CellInfo *p_cur = (RIL_CellInfo *) response;
2206     startResponse;
2207     int i;
2208     for (i = 0; i < num; i++) {
2209         appendPrintBuf("%s[%d: type=%d,registered=%d,timeStampType=%d,timeStamp=%lld", printBuf, i,
2210             p_cur->cellInfoType, p_cur->registered, p_cur->timeStampType, p_cur->timeStamp);
2211         p.writeInt32((int)p_cur->cellInfoType);
2212         p.writeInt32(p_cur->registered);
2213         p.writeInt32(p_cur->timeStampType);
2214         p.writeInt64(p_cur->timeStamp);
2215         switch(p_cur->cellInfoType) {
2216             case RIL_CELL_INFO_TYPE_GSM: {
2217                 appendPrintBuf("%s GSM id: mcc=%d,mnc=%d,lac=%d,cid=%d,psc=%d,", printBuf,
2218                     p_cur->CellInfo.gsm.cellIdentityGsm.mcc,
2219                     p_cur->CellInfo.gsm.cellIdentityGsm.mnc,
2220                     p_cur->CellInfo.gsm.cellIdentityGsm.lac,
2221                     p_cur->CellInfo.gsm.cellIdentityGsm.cid,
2222                     p_cur->CellInfo.gsm.cellIdentityGsm.psc);
2223                 appendPrintBuf("%s SS: gsmSS ss=%d,ber=%d],", printBuf,
2224                     p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength,
2225                     p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
2226
2227                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
2228                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
2229                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
2230                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
2231                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.psc);
2232                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
2233                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
2234                 break;
2235             }
2236             case RIL_CELL_INFO_TYPE_CDMA: {
2237                 appendPrintBuf("%s CDMA id: nId=%d,sId=%d,bsId=%d,long=%d,lat=%d", printBuf,
2238                     p_cur->CellInfo.cdma.cellIdentityCdma.networkId,
2239                     p_cur->CellInfo.cdma.cellIdentityCdma.systemId,
2240                     p_cur->CellInfo.cdma.cellIdentityCdma.basestationId,
2241                     p_cur->CellInfo.cdma.cellIdentityCdma.longitude,
2242                     p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
2243
2244                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
2245                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
2246                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
2247                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
2248                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
2249
2250                 appendPrintBuf("%s cdmaSS: dbm=%d ecio=%d evdoSS: dbm=%d,ecio=%d,snr=%d", printBuf,
2251                     p_cur->CellInfo.cdma.signalStrengthCdma.dbm,
2252                     p_cur->CellInfo.cdma.signalStrengthCdma.ecio,
2253                     p_cur->CellInfo.cdma.signalStrengthEvdo.dbm,
2254                     p_cur->CellInfo.cdma.signalStrengthEvdo.ecio,
2255                     p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
2256
2257                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
2258                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
2259                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
2260                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
2261                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
2262                 break;
2263             }
2264             case RIL_CELL_INFO_TYPE_LTE: {
2265                 appendPrintBuf("%s LTE id: mcc=%d,mnc=%d,ci=%d,pci=%d,tac=%d", printBuf,
2266                     p_cur->CellInfo.lte.cellIdentityLte.mcc,
2267                     p_cur->CellInfo.lte.cellIdentityLte.mnc,
2268                     p_cur->CellInfo.lte.cellIdentityLte.ci,
2269                     p_cur->CellInfo.lte.cellIdentityLte.pci,
2270                     p_cur->CellInfo.lte.cellIdentityLte.tac);
2271
2272                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
2273                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
2274                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
2275                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
2276                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
2277
2278                 appendPrintBuf("%s lteSS: ss=%d,rsrp=%d,rsrq=%d,rssnr=%d,cqi=%d,ta=%d", printBuf,
2279                     p_cur->CellInfo.lte.signalStrengthLte.signalStrength,
2280                     p_cur->CellInfo.lte.signalStrengthLte.rsrp,
2281                     p_cur->CellInfo.lte.signalStrengthLte.rsrq,
2282                     p_cur->CellInfo.lte.signalStrengthLte.rssnr,
2283                     p_cur->CellInfo.lte.signalStrengthLte.cqi,
2284                     p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
2285                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
2286                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
2287                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
2288                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
2289                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
2290                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
2291                 break;
2292             }
2293         }
2294         p_cur += 1;
2295     }
2296     removeLastChar;
2297     closeResponse;
2298
2299     return 0;
2300 }
2301
2302 static void triggerEvLoop() {
2303     int ret;
2304     if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
2305         /* trigger event loop to wakeup. No reason to do this,
2306          * if we're in the event loop thread */
2307          do {
2308             ret = write (s_fdWakeupWrite, " ", 1);
2309          } while (ret < 0 && errno == EINTR);
2310     }
2311 }
2312
2313 static void rilEventAddWakeup(struct ril_event *ev) {
2314     ril_event_add(ev);
2315     triggerEvLoop();
2316 }
2317
2318 static void sendSimStatusAppInfo(Parcel &p, int num_apps, RIL_AppStatus appStatus[]) {
2319         p.writeInt32(num_apps);
2320         startResponse;
2321         for (int i = 0; i < num_apps; i++) {
2322             p.writeInt32(appStatus[i].app_type);
2323             p.writeInt32(appStatus[i].app_state);
2324             p.writeInt32(appStatus[i].perso_substate);
2325             writeStringToParcel(p, (const char*)(appStatus[i].aid_ptr));
2326             writeStringToParcel(p, (const char*)
2327                                           (appStatus[i].app_label_ptr));
2328             p.writeInt32(appStatus[i].pin1_replaced);
2329             p.writeInt32(appStatus[i].pin1);
2330             p.writeInt32(appStatus[i].pin2);
2331             appendPrintBuf("%s[app_type=%d,app_state=%d,perso_substate=%d,\
2332                     aid_ptr=%s,app_label_ptr=%s,pin1_replaced=%d,pin1=%d,pin2=%d],",
2333                     printBuf,
2334                     appStatus[i].app_type,
2335                     appStatus[i].app_state,
2336                     appStatus[i].perso_substate,
2337                     appStatus[i].aid_ptr,
2338                     appStatus[i].app_label_ptr,
2339                     appStatus[i].pin1_replaced,
2340                     appStatus[i].pin1,
2341                     appStatus[i].pin2);
2342         }
2343         closeResponse;
2344 }
2345
2346 static int responseSimStatus(Parcel &p, void *response, size_t responselen) {
2347     int i;
2348
2349     if (response == NULL && responselen != 0) {
2350         RLOGE("invalid response: NULL");
2351         return RIL_ERRNO_INVALID_RESPONSE;
2352     }
2353
2354     if (responselen == sizeof (RIL_CardStatus_v6)) {
2355         RIL_CardStatus_v6 *p_cur = ((RIL_CardStatus_v6 *) response);
2356
2357         p.writeInt32(p_cur->card_state);
2358         p.writeInt32(p_cur->universal_pin_state);
2359         p.writeInt32(p_cur->gsm_umts_subscription_app_index);
2360         p.writeInt32(p_cur->cdma_subscription_app_index);
2361         p.writeInt32(p_cur->ims_subscription_app_index);
2362
2363         sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
2364     } else if (responselen == sizeof (RIL_CardStatus_v5)) {
2365         RIL_CardStatus_v5 *p_cur = ((RIL_CardStatus_v5 *) response);
2366
2367         p.writeInt32(p_cur->card_state);
2368         p.writeInt32(p_cur->universal_pin_state);
2369         p.writeInt32(p_cur->gsm_umts_subscription_app_index);
2370         p.writeInt32(p_cur->cdma_subscription_app_index);
2371         p.writeInt32(-1);
2372
2373         sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
2374     } else {
2375         RLOGE("responseSimStatus: A RilCardStatus_v6 or _v5 expected\n");
2376         return RIL_ERRNO_INVALID_RESPONSE;
2377     }
2378
2379     return 0;
2380 }
2381
2382 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2383     int num = responselen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
2384     p.writeInt32(num);
2385
2386     startResponse;
2387     RIL_GSM_BroadcastSmsConfigInfo **p_cur =
2388                 (RIL_GSM_BroadcastSmsConfigInfo **) response;
2389     for (int i = 0; i < num; i++) {
2390         p.writeInt32(p_cur[i]->fromServiceId);
2391         p.writeInt32(p_cur[i]->toServiceId);
2392         p.writeInt32(p_cur[i]->fromCodeScheme);
2393         p.writeInt32(p_cur[i]->toCodeScheme);
2394         p.writeInt32(p_cur[i]->selected);
2395
2396         appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId=%d, \
2397                 fromCodeScheme=%d, toCodeScheme=%d, selected =%d]",
2398                 printBuf, i, p_cur[i]->fromServiceId, p_cur[i]->toServiceId,
2399                 p_cur[i]->fromCodeScheme, p_cur[i]->toCodeScheme,
2400                 p_cur[i]->selected);
2401     }
2402     closeResponse;
2403
2404     return 0;
2405 }
2406
2407 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2408     RIL_CDMA_BroadcastSmsConfigInfo **p_cur =
2409                (RIL_CDMA_BroadcastSmsConfigInfo **) response;
2410
2411     int num = responselen / sizeof (RIL_CDMA_BroadcastSmsConfigInfo *);
2412     p.writeInt32(num);
2413
2414     startResponse;
2415     for (int i = 0 ; i < num ; i++ ) {
2416         p.writeInt32(p_cur[i]->service_category);
2417         p.writeInt32(p_cur[i]->language);
2418         p.writeInt32(p_cur[i]->selected);
2419
2420         appendPrintBuf("%s [%d: srvice_category=%d, language =%d, \
2421               selected =%d], ",
2422               printBuf, i, p_cur[i]->service_category, p_cur[i]->language,
2423               p_cur[i]->selected);
2424     }
2425     closeResponse;
2426
2427     return 0;
2428 }
2429
2430 static int responseCdmaSms(Parcel &p, void *response, size_t responselen) {
2431     int num;
2432     int digitCount;
2433     int digitLimit;
2434     uint8_t uct;
2435     void* dest;
2436
2437     RLOGD("Inside responseCdmaSms");
2438
2439     if (response == NULL && responselen != 0) {
2440         RLOGE("invalid response: NULL");
2441         return RIL_ERRNO_INVALID_RESPONSE;
2442     }
2443
2444     if (responselen != sizeof(RIL_CDMA_SMS_Message)) {
2445         RLOGE("invalid response length was %d expected %d",
2446                 (int)responselen, (int)sizeof(RIL_CDMA_SMS_Message));
2447         return RIL_ERRNO_INVALID_RESPONSE;
2448     }
2449
2450     RIL_CDMA_SMS_Message *p_cur = (RIL_CDMA_SMS_Message *) response;
2451     p.writeInt32(p_cur->uTeleserviceID);
2452     p.write(&(p_cur->bIsServicePresent),sizeof(uct));
2453     p.writeInt32(p_cur->uServicecategory);
2454     p.writeInt32(p_cur->sAddress.digit_mode);
2455     p.writeInt32(p_cur->sAddress.number_mode);
2456     p.writeInt32(p_cur->sAddress.number_type);
2457     p.writeInt32(p_cur->sAddress.number_plan);
2458     p.write(&(p_cur->sAddress.number_of_digits), sizeof(uct));
2459     digitLimit= MIN((p_cur->sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
2460     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2461         p.write(&(p_cur->sAddress.digits[digitCount]),sizeof(uct));
2462     }
2463
2464     p.writeInt32(p_cur->sSubAddress.subaddressType);
2465     p.write(&(p_cur->sSubAddress.odd),sizeof(uct));
2466     p.write(&(p_cur->sSubAddress.number_of_digits),sizeof(uct));
2467     digitLimit= MIN((p_cur->sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
2468     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2469         p.write(&(p_cur->sSubAddress.digits[digitCount]),sizeof(uct));
2470     }
2471
2472     digitLimit= MIN((p_cur->uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
2473     p.writeInt32(p_cur->uBearerDataLen);
2474     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2475        p.write(&(p_cur->aBearerData[digitCount]), sizeof(uct));
2476     }
2477
2478     startResponse;
2479     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
2480             sAddress.digit_mode=%d, sAddress.number_mode=%d, sAddress.number_type=%d, ",
2481             printBuf, p_cur->uTeleserviceID,p_cur->bIsServicePresent,p_cur->uServicecategory,
2482             p_cur->sAddress.digit_mode, p_cur->sAddress.number_mode,p_cur->sAddress.number_type);
2483     closeResponse;
2484
2485     return 0;
2486 }
2487
2488 /**
2489  * A write on the wakeup fd is done just to pop us out of select()
2490  * We empty the buffer here and then ril_event will reset the timers on the
2491  * way back down
2492  */
2493 static void processWakeupCallback(int fd, short flags, void *param) {
2494     char buff[16];
2495     int ret;
2496
2497     RLOGV("processWakeupCallback");
2498
2499     /* empty our wakeup socket out */
2500     do {
2501         ret = read(s_fdWakeupRead, &buff, sizeof(buff));
2502     } while (ret > 0 || (ret < 0 && errno == EINTR));
2503 }
2504
2505 static void onCommandsSocketClosed() {
2506     int ret;
2507     RequestInfo *p_cur;
2508
2509     /* mark pending requests as "cancelled" so we dont report responses */
2510
2511     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
2512     assert (ret == 0);
2513
2514     p_cur = s_pendingRequests;
2515
2516     for (p_cur = s_pendingRequests
2517             ; p_cur != NULL
2518             ; p_cur  = p_cur->p_next
2519     ) {
2520         p_cur->cancelled = 1;
2521     }
2522
2523     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
2524     assert (ret == 0);
2525 }
2526
2527 static void processCommandsCallback(int fd, short flags, void *param) {
2528     RecordStream *p_rs;
2529     void *p_record;
2530     size_t recordlen;
2531     int ret;
2532
2533     assert(fd == s_fdCommand);
2534
2535     p_rs = (RecordStream *)param;
2536
2537     for (;;) {
2538         /* loop until EAGAIN/EINTR, end of stream, or other error */
2539         ret = record_stream_get_next(p_rs, &p_record, &recordlen);
2540
2541         if (ret == 0 && p_record == NULL) {
2542             /* end-of-stream */
2543             break;
2544         } else if (ret < 0) {
2545             break;
2546         } else if (ret == 0) { /* && p_record != NULL */
2547             processCommandBuffer(p_record, recordlen);
2548         }
2549     }
2550
2551     if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
2552         /* fatal error or end-of-stream */
2553         if (ret != 0) {
2554             RLOGE("error on reading command socket errno:%d\n", errno);
2555         } else {
2556             RLOGW("EOS.  Closing command socket.");
2557         }
2558
2559         close(s_fdCommand);
2560         s_fdCommand = -1;
2561
2562         ril_event_del(&s_commands_event);
2563
2564         record_stream_free(p_rs);
2565
2566         /* start listening for new connections again */
2567         rilEventAddWakeup(&s_listen_event);
2568
2569         onCommandsSocketClosed();
2570     }
2571 }
2572
2573
2574 static void onNewCommandConnect() {
2575     // Inform we are connected and the ril version
2576     int rilVer = s_callbacks.version;
2577     RIL_onUnsolicitedResponse(RIL_UNSOL_RIL_CONNECTED,
2578                                     &rilVer, sizeof(rilVer));
2579
2580     // implicit radio state changed
2581     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
2582                                     NULL, 0);
2583
2584     // Send last NITZ time data, in case it was missed
2585     if (s_lastNITZTimeData != NULL) {
2586         sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize);
2587
2588         free(s_lastNITZTimeData);
2589         s_lastNITZTimeData = NULL;
2590     }
2591
2592     // Get version string
2593     if (s_callbacks.getVersion != NULL) {
2594         const char *version;
2595         version = s_callbacks.getVersion();
2596         RLOGI("RIL Daemon version: %s\n", version);
2597
2598         property_set(PROPERTY_RIL_IMPL, version);
2599     } else {
2600         RLOGI("RIL Daemon version: unavailable\n");
2601         property_set(PROPERTY_RIL_IMPL, "unavailable");
2602     }
2603
2604 }
2605
2606 static void listenCallback (int fd, short flags, void *param) {
2607     int ret;
2608     int err;
2609     int is_phone_socket;
2610     RecordStream *p_rs;
2611
2612     struct sockaddr_un peeraddr;
2613     socklen_t socklen = sizeof (peeraddr);
2614
2615     struct ucred creds;
2616     socklen_t szCreds = sizeof(creds);
2617
2618     struct passwd *pwd = NULL;
2619
2620     assert (s_fdCommand < 0);
2621     assert (fd == s_fdListen);
2622
2623     s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen);
2624
2625     if (s_fdCommand < 0 ) {
2626         RLOGE("Error on accept() errno:%d", errno);
2627         /* start listening for new connections again */
2628         rilEventAddWakeup(&s_listen_event);
2629               return;
2630     }
2631
2632     /* check the credential of the other side and only accept socket from
2633      * phone process
2634      */
2635     errno = 0;
2636     is_phone_socket = 0;
2637
2638     err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
2639
2640     if (err == 0 && szCreds > 0) {
2641         errno = 0;
2642         pwd = getpwuid(creds.uid);
2643         if (pwd != NULL) {
2644             if (strcmp(pwd->pw_name, PHONE_PROCESS) == 0) {
2645                 is_phone_socket = 1;
2646             } else {
2647                 RLOGE("RILD can't accept socket from process %s", pwd->pw_name);
2648             }
2649         } else {
2650             RLOGE("Error on getpwuid() errno: %d", errno);
2651         }
2652     } else {
2653         RLOGD("Error on getsockopt() errno: %d", errno);
2654     }
2655
2656     if ( !is_phone_socket ) {
2657       RLOGE("RILD must accept socket from %s", PHONE_PROCESS);
2658
2659       close(s_fdCommand);
2660       s_fdCommand = -1;
2661
2662       onCommandsSocketClosed();
2663
2664       /* start listening for new connections again */
2665       rilEventAddWakeup(&s_listen_event);
2666
2667       return;
2668     }
2669
2670     ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK);
2671
2672     if (ret < 0) {
2673         RLOGE ("Error setting O_NONBLOCK errno:%d", errno);
2674     }
2675
2676     RLOGI("libril: new connection");
2677
2678     p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES);
2679
2680     ril_event_set (&s_commands_event, s_fdCommand, 1,
2681         processCommandsCallback, p_rs);
2682
2683     rilEventAddWakeup (&s_commands_event);
2684
2685     onNewCommandConnect();
2686 }
2687
2688 static void freeDebugCallbackArgs(int number, char **args) {
2689     for (int i = 0; i < number; i++) {
2690         if (args[i] != NULL) {
2691             free(args[i]);
2692         }
2693     }
2694     free(args);
2695 }
2696
2697 static void debugCallback (int fd, short flags, void *param) {
2698     int acceptFD, option;
2699     struct sockaddr_un peeraddr;
2700     socklen_t socklen = sizeof (peeraddr);
2701     int data;
2702     unsigned int qxdm_data[6];
2703     const char *deactData[1] = {"1"};
2704     char *actData[1];
2705     RIL_Dial dialData;
2706     int hangupData[1] = {1};
2707     int number;
2708     char **args;
2709
2710     acceptFD = accept (fd,  (sockaddr *) &peeraddr, &socklen);
2711
2712     if (acceptFD < 0) {
2713         RLOGE ("error accepting on debug port: %d\n", errno);
2714         return;
2715     }
2716
2717     if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
2718         RLOGE ("error reading on socket: number of Args: \n");
2719         return;
2720     }
2721     args = (char **) malloc(sizeof(char*) * number);
2722
2723     for (int i = 0; i < number; i++) {
2724         int len;
2725         if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
2726             RLOGE ("error reading on socket: Len of Args: \n");
2727             freeDebugCallbackArgs(i, args);
2728             return;
2729         }
2730         // +1 for null-term
2731         args[i] = (char *) malloc((sizeof(char) * len) + 1);
2732         if (recv(acceptFD, args[i], sizeof(char) * len, 0)
2733             != (int)sizeof(char) * len) {
2734             RLOGE ("error reading on socket: Args[%d] \n", i);
2735             freeDebugCallbackArgs(i, args);
2736             return;
2737         }
2738         char * buf = args[i];
2739         buf[len] = 0;
2740     }
2741
2742     switch (atoi(args[0])) {
2743         case 0:
2744             RLOGI ("Connection on debug port: issuing reset.");
2745             issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0);
2746             break;
2747         case 1:
2748             RLOGI ("Connection on debug port: issuing radio power off.");
2749             data = 0;
2750             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2751             // Close the socket
2752             close(s_fdCommand);
2753             s_fdCommand = -1;
2754             break;
2755         case 2:
2756             RLOGI ("Debug port: issuing unsolicited voice network change.");
2757             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
2758                                       NULL, 0);
2759             break;
2760         case 3:
2761             RLOGI ("Debug port: QXDM log enable.");
2762             qxdm_data[0] = 65536;     // head.func_tag
2763             qxdm_data[1] = 16;        // head.len
2764             qxdm_data[2] = 1;         // mode: 1 for 'start logging'
2765             qxdm_data[3] = 32;        // log_file_size: 32megabytes
2766             qxdm_data[4] = 0;         // log_mask
2767             qxdm_data[5] = 8;         // log_max_fileindex
2768             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2769                               6 * sizeof(int));
2770             break;
2771         case 4:
2772             RLOGI ("Debug port: QXDM log disable.");
2773             qxdm_data[0] = 65536;
2774             qxdm_data[1] = 16;
2775             qxdm_data[2] = 0;          // mode: 0 for 'stop logging'
2776             qxdm_data[3] = 32;
2777             qxdm_data[4] = 0;
2778             qxdm_data[5] = 8;
2779             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2780                               6 * sizeof(int));
2781             break;
2782         case 5:
2783             RLOGI("Debug port: Radio On");
2784             data = 1;
2785             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2786             sleep(2);
2787             // Set network selection automatic.
2788             issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0);
2789             break;
2790         case 6:
2791             RLOGI("Debug port: Setup Data Call, Apn :%s\n", args[1]);
2792             actData[0] = args[1];
2793             issueLocalRequest(RIL_REQUEST_SETUP_DATA_CALL, &actData,
2794                               sizeof(actData));
2795             break;
2796         case 7:
2797             RLOGI("Debug port: Deactivate Data Call");
2798             issueLocalRequest(RIL_REQUEST_DEACTIVATE_DATA_CALL, &deactData,
2799                               sizeof(deactData));
2800             break;
2801         case 8:
2802             RLOGI("Debug port: Dial Call");
2803             dialData.clir = 0;
2804             dialData.address = args[1];
2805             issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData));
2806             break;
2807         case 9:
2808             RLOGI("Debug port: Answer Call");
2809             issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0);
2810             break;
2811         case 10:
2812             RLOGI("Debug port: End Call");
2813             issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
2814                               sizeof(hangupData));
2815             break;
2816         default:
2817             RLOGE ("Invalid request");
2818             break;
2819     }
2820     freeDebugCallbackArgs(number, args);
2821     close(acceptFD);
2822 }
2823
2824
2825 static void userTimerCallback (int fd, short flags, void *param) {
2826     UserCallbackInfo *p_info;
2827
2828     p_info = (UserCallbackInfo *)param;
2829
2830     p_info->p_callback(p_info->userParam);
2831
2832
2833     // FIXME generalize this...there should be a cancel mechanism
2834     if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
2835         s_last_wake_timeout_info = NULL;
2836     }
2837
2838     free(p_info);
2839 }
2840
2841
2842 static void *
2843 eventLoop(void *param) {
2844     int ret;
2845     int filedes[2];
2846
2847     ril_event_init();
2848
2849     pthread_mutex_lock(&s_startupMutex);
2850
2851     s_started = 1;
2852     pthread_cond_broadcast(&s_startupCond);
2853
2854     pthread_mutex_unlock(&s_startupMutex);
2855
2856     ret = pipe(filedes);
2857
2858     if (ret < 0) {
2859         RLOGE("Error in pipe() errno:%d", errno);
2860         return NULL;
2861     }
2862
2863     s_fdWakeupRead = filedes[0];
2864     s_fdWakeupWrite = filedes[1];
2865
2866     fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
2867
2868     ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
2869                 processWakeupCallback, NULL);
2870
2871     rilEventAddWakeup (&s_wakeupfd_event);
2872
2873     // Only returns on error
2874     ril_event_loop();
2875     RLOGE ("error in event_loop_base errno:%d", errno);
2876     // kill self to restart on error
2877     kill(0, SIGKILL);
2878
2879     return NULL;
2880 }
2881
2882 extern "C" void
2883 RIL_startEventLoop(void) {
2884     int ret;
2885     pthread_attr_t attr;
2886
2887     /* spin up eventLoop thread and wait for it to get started */
2888     s_started = 0;
2889     pthread_mutex_lock(&s_startupMutex);
2890
2891     pthread_attr_init (&attr);
2892     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2893     ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
2894
2895     while (s_started == 0) {
2896         pthread_cond_wait(&s_startupCond, &s_startupMutex);
2897     }
2898
2899     pthread_mutex_unlock(&s_startupMutex);
2900
2901     if (ret < 0) {
2902         RLOGE("Failed to create dispatch thread errno:%d", errno);
2903         return;
2904     }
2905 }
2906
2907 // Used for testing purpose only.
2908 extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
2909     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
2910 }
2911
2912 extern "C" void
2913 RIL_register (const RIL_RadioFunctions *callbacks) {
2914     int ret;
2915     int flags;
2916
2917     if (callbacks == NULL) {
2918         RLOGE("RIL_register: RIL_RadioFunctions * null");
2919         return;
2920     }
2921     if (callbacks->version < RIL_VERSION_MIN) {
2922         RLOGE("RIL_register: version %d is to old, min version is %d",
2923              callbacks->version, RIL_VERSION_MIN);
2924         return;
2925     }
2926     if (callbacks->version > RIL_VERSION) {
2927         RLOGE("RIL_register: version %d is too new, max version is %d",
2928              callbacks->version, RIL_VERSION);
2929         return;
2930     }
2931     RLOGE("RIL_register: RIL version %d", callbacks->version);
2932
2933     if (s_registerCalled > 0) {
2934         RLOGE("RIL_register has been called more than once. "
2935                 "Subsequent call ignored");
2936         return;
2937     }
2938
2939     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
2940
2941     s_registerCalled = 1;
2942
2943     // Little self-check
2944
2945     for (int i = 0; i < (int)NUM_ELEMS(s_commands); i++) {
2946         assert(i == s_commands[i].requestNumber);
2947     }
2948
2949     for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses); i++) {
2950         assert(i + RIL_UNSOL_RESPONSE_BASE
2951                 == s_unsolResponses[i].requestNumber);
2952     }
2953
2954     // New rild impl calls RIL_startEventLoop() first
2955     // old standalone impl wants it here.
2956
2957     if (s_started == 0) {
2958         RIL_startEventLoop();
2959     }
2960
2961     // start listen socket
2962
2963 #if 0
2964     ret = socket_local_server (SOCKET_NAME_RIL,
2965             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
2966
2967     if (ret < 0) {
2968         RLOGE("Unable to bind socket errno:%d", errno);
2969         exit (-1);
2970     }
2971     s_fdListen = ret;
2972
2973 #else
2974     s_fdListen = android_get_control_socket(SOCKET_NAME_RIL);
2975     if (s_fdListen < 0) {
2976         RLOGE("Failed to get socket '" SOCKET_NAME_RIL "'");
2977         exit(-1);
2978     }
2979
2980     ret = listen(s_fdListen, 4);
2981
2982     if (ret < 0) {
2983         RLOGE("Failed to listen on control socket '%d': %s",
2984              s_fdListen, strerror(errno));
2985         exit(-1);
2986     }
2987 #endif
2988
2989
2990     /* note: non-persistent so we can accept only one connection at a time */
2991     ril_event_set (&s_listen_event, s_fdListen, false,
2992                 listenCallback, NULL);
2993
2994     rilEventAddWakeup (&s_listen_event);
2995
2996 #if 1
2997     // start debug interface socket
2998
2999     s_fdDebug = android_get_control_socket(SOCKET_NAME_RIL_DEBUG);
3000     if (s_fdDebug < 0) {
3001         RLOGE("Failed to get socket '" SOCKET_NAME_RIL_DEBUG "' errno:%d", errno);
3002         exit(-1);
3003     }
3004
3005     ret = listen(s_fdDebug, 4);
3006
3007     if (ret < 0) {
3008         RLOGE("Failed to listen on ril debug socket '%d': %s",
3009              s_fdDebug, strerror(errno));
3010         exit(-1);
3011     }
3012
3013     ril_event_set (&s_debug_event, s_fdDebug, true,
3014                 debugCallback, NULL);
3015
3016     rilEventAddWakeup (&s_debug_event);
3017 #endif
3018
3019 }
3020
3021 static int
3022 checkAndDequeueRequestInfo(struct RequestInfo *pRI) {
3023     int ret = 0;
3024
3025     if (pRI == NULL) {
3026         return 0;
3027     }
3028
3029     pthread_mutex_lock(&s_pendingRequestsMutex);
3030
3031     for(RequestInfo **ppCur = &s_pendingRequests
3032         ; *ppCur != NULL
3033         ; ppCur = &((*ppCur)->p_next)
3034     ) {
3035         if (pRI == *ppCur) {
3036             ret = 1;
3037
3038             *ppCur = (*ppCur)->p_next;
3039             break;
3040         }
3041     }
3042
3043     pthread_mutex_unlock(&s_pendingRequestsMutex);
3044
3045     return ret;
3046 }
3047
3048
3049 extern "C" void
3050 RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen) {
3051     RequestInfo *pRI;
3052     int ret;
3053     size_t errorOffset;
3054
3055     pRI = (RequestInfo *)t;
3056
3057     if (!checkAndDequeueRequestInfo(pRI)) {
3058         RLOGE ("RIL_onRequestComplete: invalid RIL_Token");
3059         return;
3060     }
3061
3062     if (pRI->local > 0) {
3063         // Locally issued command...void only!
3064         // response does not go back up the command socket
3065         RLOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
3066
3067         goto done;
3068     }
3069
3070     appendPrintBuf("[%04d]< %s",
3071         pRI->token, requestToString(pRI->pCI->requestNumber));
3072
3073     if (pRI->cancelled == 0) {
3074         Parcel p;
3075
3076         p.writeInt32 (RESPONSE_SOLICITED);
3077         p.writeInt32 (pRI->token);
3078         errorOffset = p.dataPosition();
3079
3080         p.writeInt32 (e);
3081
3082         if (response != NULL) {
3083             // there is a response payload, no matter success or not.
3084             ret = pRI->pCI->responseFunction(p, response, responselen);
3085
3086             /* if an error occurred, rewind and mark it */
3087             if (ret != 0) {
3088                 p.setDataPosition(errorOffset);
3089                 p.writeInt32 (ret);
3090             }
3091         }
3092
3093         if (e != RIL_E_SUCCESS) {
3094             appendPrintBuf("%s fails by %s", printBuf, failCauseToString(e));
3095         }
3096
3097         if (s_fdCommand < 0) {
3098             RLOGD ("RIL onRequestComplete: Command channel closed");
3099         }
3100         sendResponse(p);
3101     }
3102
3103 done:
3104     free(pRI);
3105 }
3106
3107
3108 static void
3109 grabPartialWakeLock() {
3110     acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
3111 }
3112
3113 static void
3114 releaseWakeLock() {
3115     release_wake_lock(ANDROID_WAKE_LOCK_NAME);
3116 }
3117
3118 /**
3119  * Timer callback to put us back to sleep before the default timeout
3120  */
3121 static void
3122 wakeTimeoutCallback (void *param) {
3123     // We're using "param != NULL" as a cancellation mechanism
3124     if (param == NULL) {
3125         //RLOGD("wakeTimeout: releasing wake lock");
3126
3127         releaseWakeLock();
3128     } else {
3129         //RLOGD("wakeTimeout: releasing wake lock CANCELLED");
3130     }
3131 }
3132
3133 static int
3134 decodeVoiceRadioTechnology (RIL_RadioState radioState) {
3135     switch (radioState) {
3136         case RADIO_STATE_SIM_NOT_READY:
3137         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3138         case RADIO_STATE_SIM_READY:
3139             return RADIO_TECH_UMTS;
3140
3141         case RADIO_STATE_RUIM_NOT_READY:
3142         case RADIO_STATE_RUIM_READY:
3143         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3144         case RADIO_STATE_NV_NOT_READY:
3145         case RADIO_STATE_NV_READY:
3146             return RADIO_TECH_1xRTT;
3147
3148         default:
3149             RLOGD("decodeVoiceRadioTechnology: Invoked with incorrect RadioState");
3150             return -1;
3151     }
3152 }
3153
3154 static int
3155 decodeCdmaSubscriptionSource (RIL_RadioState radioState) {
3156     switch (radioState) {
3157         case RADIO_STATE_SIM_NOT_READY:
3158         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3159         case RADIO_STATE_SIM_READY:
3160         case RADIO_STATE_RUIM_NOT_READY:
3161         case RADIO_STATE_RUIM_READY:
3162         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3163             return CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM;
3164
3165         case RADIO_STATE_NV_NOT_READY:
3166         case RADIO_STATE_NV_READY:
3167             return CDMA_SUBSCRIPTION_SOURCE_NV;
3168
3169         default:
3170             RLOGD("decodeCdmaSubscriptionSource: Invoked with incorrect RadioState");
3171             return -1;
3172     }
3173 }
3174
3175 static int
3176 decodeSimStatus (RIL_RadioState radioState) {
3177    switch (radioState) {
3178        case RADIO_STATE_SIM_NOT_READY:
3179        case RADIO_STATE_RUIM_NOT_READY:
3180        case RADIO_STATE_NV_NOT_READY:
3181        case RADIO_STATE_NV_READY:
3182            return -1;
3183        case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3184        case RADIO_STATE_SIM_READY:
3185        case RADIO_STATE_RUIM_READY:
3186        case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3187            return radioState;
3188        default:
3189            RLOGD("decodeSimStatus: Invoked with incorrect RadioState");
3190            return -1;
3191    }
3192 }
3193
3194 static bool is3gpp2(int radioTech) {
3195     switch (radioTech) {
3196         case RADIO_TECH_IS95A:
3197         case RADIO_TECH_IS95B:
3198         case RADIO_TECH_1xRTT:
3199         case RADIO_TECH_EVDO_0:
3200         case RADIO_TECH_EVDO_A:
3201         case RADIO_TECH_EVDO_B:
3202         case RADIO_TECH_EHRPD:
3203             return true;
3204         default:
3205             return false;
3206     }
3207 }
3208
3209 /* If RIL sends SIM states or RUIM states, store the voice radio
3210  * technology and subscription source information so that they can be
3211  * returned when telephony framework requests them
3212  */
3213 static RIL_RadioState
3214 processRadioState(RIL_RadioState newRadioState) {
3215
3216     if((newRadioState > RADIO_STATE_UNAVAILABLE) && (newRadioState < RADIO_STATE_ON)) {
3217         int newVoiceRadioTech;
3218         int newCdmaSubscriptionSource;
3219         int newSimStatus;
3220
3221         /* This is old RIL. Decode Subscription source and Voice Radio Technology
3222            from Radio State and send change notifications if there has been a change */
3223         newVoiceRadioTech = decodeVoiceRadioTechnology(newRadioState);
3224         if(newVoiceRadioTech != voiceRadioTech) {
3225             voiceRadioTech = newVoiceRadioTech;
3226             RIL_onUnsolicitedResponse (RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
3227                         &voiceRadioTech, sizeof(voiceRadioTech));
3228         }
3229         if(is3gpp2(newVoiceRadioTech)) {
3230             newCdmaSubscriptionSource = decodeCdmaSubscriptionSource(newRadioState);
3231             if(newCdmaSubscriptionSource != cdmaSubscriptionSource) {
3232                 cdmaSubscriptionSource = newCdmaSubscriptionSource;
3233                 RIL_onUnsolicitedResponse (RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
3234                         &cdmaSubscriptionSource, sizeof(cdmaSubscriptionSource));
3235             }
3236         }
3237         newSimStatus = decodeSimStatus(newRadioState);
3238         if(newSimStatus != simRuimStatus) {
3239             simRuimStatus = newSimStatus;
3240             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
3241         }
3242
3243         /* Send RADIO_ON to telephony */
3244         newRadioState = RADIO_STATE_ON;
3245     }
3246
3247     return newRadioState;
3248 }
3249
3250 extern "C"
3251 void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
3252                                 size_t datalen)
3253 {
3254     int unsolResponseIndex;
3255     int ret;
3256     int64_t timeReceived = 0;
3257     bool shouldScheduleTimeout = false;
3258     RIL_RadioState newState;
3259
3260     if (s_registerCalled == 0) {
3261         // Ignore RIL_onUnsolicitedResponse before RIL_register
3262         RLOGW("RIL_onUnsolicitedResponse called before RIL_register");
3263         return;
3264     }
3265
3266     unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
3267
3268     if ((unsolResponseIndex < 0)
3269         || (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
3270         RLOGE("unsupported unsolicited response code %d", unsolResponse);
3271         return;
3272     }
3273
3274     // Grab a wake lock if needed for this reponse,
3275     // as we exit we'll either release it immediately
3276     // or set a timer to release it later.
3277     switch (s_unsolResponses[unsolResponseIndex].wakeType) {
3278         case WAKE_PARTIAL:
3279             grabPartialWakeLock();
3280             shouldScheduleTimeout = true;
3281         break;
3282
3283         case DONT_WAKE:
3284         default:
3285             // No wake lock is grabed so don't set timeout
3286             shouldScheduleTimeout = false;
3287             break;
3288     }
3289
3290     // Mark the time this was received, doing this
3291     // after grabing the wakelock incase getting
3292     // the elapsedRealTime might cause us to goto
3293     // sleep.
3294     if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
3295         timeReceived = elapsedRealtime();
3296     }
3297
3298     appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
3299
3300     Parcel p;
3301
3302     p.writeInt32 (RESPONSE_UNSOLICITED);
3303     p.writeInt32 (unsolResponse);
3304
3305     ret = s_unsolResponses[unsolResponseIndex]
3306                 .responseFunction(p, data, datalen);
3307     if (ret != 0) {
3308         // Problem with the response. Don't continue;
3309         goto error_exit;
3310     }
3311
3312     // some things get more payload
3313     switch(unsolResponse) {
3314         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
3315             newState = processRadioState(s_callbacks.onStateRequest());
3316             p.writeInt32(newState);
3317             appendPrintBuf("%s {%s}", printBuf,
3318                 radioStateToString(s_callbacks.onStateRequest()));
3319         break;
3320
3321
3322         case RIL_UNSOL_NITZ_TIME_RECEIVED:
3323             // Store the time that this was received so the
3324             // handler of this message can account for
3325             // the time it takes to arrive and process. In
3326             // particular the system has been known to sleep
3327             // before this message can be processed.
3328             p.writeInt64(timeReceived);
3329         break;
3330     }
3331
3332     ret = sendResponse(p);
3333     if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
3334
3335         // Unfortunately, NITZ time is not poll/update like everything
3336         // else in the system. So, if the upstream client isn't connected,
3337         // keep a copy of the last NITZ response (with receive time noted
3338         // above) around so we can deliver it when it is connected
3339
3340         if (s_lastNITZTimeData != NULL) {
3341             free (s_lastNITZTimeData);
3342             s_lastNITZTimeData = NULL;
3343         }
3344
3345         s_lastNITZTimeData = malloc(p.dataSize());
3346         s_lastNITZTimeDataSize = p.dataSize();
3347         memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
3348     }
3349
3350     // For now, we automatically go back to sleep after TIMEVAL_WAKE_TIMEOUT
3351     // FIXME The java code should handshake here to release wake lock
3352
3353     if (shouldScheduleTimeout) {
3354         // Cancel the previous request
3355         if (s_last_wake_timeout_info != NULL) {
3356             s_last_wake_timeout_info->userParam = (void *)1;
3357         }
3358
3359         s_last_wake_timeout_info
3360             = internalRequestTimedCallback(wakeTimeoutCallback, NULL,
3361                                             &TIMEVAL_WAKE_TIMEOUT);
3362     }
3363
3364     // Normal exit
3365     return;
3366
3367 error_exit:
3368     if (shouldScheduleTimeout) {
3369         releaseWakeLock();
3370     }
3371 }
3372
3373 /** FIXME generalize this if you track UserCAllbackInfo, clear it
3374     when the callback occurs
3375 */
3376 static UserCallbackInfo *
3377 internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
3378                                 const struct timeval *relativeTime)
3379 {
3380     struct timeval myRelativeTime;
3381     UserCallbackInfo *p_info;
3382
3383     p_info = (UserCallbackInfo *) malloc (sizeof(UserCallbackInfo));
3384
3385     p_info->p_callback = callback;
3386     p_info->userParam = param;
3387
3388     if (relativeTime == NULL) {
3389         /* treat null parameter as a 0 relative time */
3390         memset (&myRelativeTime, 0, sizeof(myRelativeTime));
3391     } else {
3392         /* FIXME I think event_add's tv param is really const anyway */
3393         memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
3394     }
3395
3396     ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
3397
3398     ril_timer_add(&(p_info->event), &myRelativeTime);
3399
3400     triggerEvLoop();
3401     return p_info;
3402 }
3403
3404
3405 extern "C" void
3406 RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
3407                                 const struct timeval *relativeTime) {
3408     internalRequestTimedCallback (callback, param, relativeTime);
3409 }
3410
3411 const char *
3412 failCauseToString(RIL_Errno e) {
3413     switch(e) {
3414         case RIL_E_SUCCESS: return "E_SUCCESS";
3415         case RIL_E_RADIO_NOT_AVAILABLE: return "E_RAIDO_NOT_AVAILABLE";
3416         case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
3417         case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
3418         case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
3419         case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
3420         case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
3421         case RIL_E_CANCELLED: return "E_CANCELLED";
3422         case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
3423         case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
3424         case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
3425         case RIL_E_SIM_ABSENT:return "E_SIM_ABSENT";
3426         case RIL_E_ILLEGAL_SIM_OR_ME:return "E_ILLEGAL_SIM_OR_ME";
3427 #ifdef FEATURE_MULTIMODE_ANDROID
3428         case RIL_E_SUBSCRIPTION_NOT_AVAILABLE:return "E_SUBSCRIPTION_NOT_AVAILABLE";
3429         case RIL_E_MODE_NOT_SUPPORTED:return "E_MODE_NOT_SUPPORTED";
3430 #endif
3431         default: return "<unknown error>";
3432     }
3433 }
3434
3435 const char *
3436 radioStateToString(RIL_RadioState s) {
3437     switch(s) {
3438         case RADIO_STATE_OFF: return "RADIO_OFF";
3439         case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
3440         case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
3441         case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
3442         case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
3443         case RADIO_STATE_RUIM_NOT_READY:return"RADIO_RUIM_NOT_READY";
3444         case RADIO_STATE_RUIM_READY:return"RADIO_RUIM_READY";
3445         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:return"RADIO_RUIM_LOCKED_OR_ABSENT";
3446         case RADIO_STATE_NV_NOT_READY:return"RADIO_NV_NOT_READY";
3447         case RADIO_STATE_NV_READY:return"RADIO_NV_READY";
3448         case RADIO_STATE_ON:return"RADIO_ON";
3449         default: return "<unknown state>";
3450     }
3451 }
3452
3453 const char *
3454 callStateToString(RIL_CallState s) {
3455     switch(s) {
3456         case RIL_CALL_ACTIVE : return "ACTIVE";
3457         case RIL_CALL_HOLDING: return "HOLDING";
3458         case RIL_CALL_DIALING: return "DIALING";
3459         case RIL_CALL_ALERTING: return "ALERTING";
3460         case RIL_CALL_INCOMING: return "INCOMING";
3461         case RIL_CALL_WAITING: return "WAITING";
3462         default: return "<unknown state>";
3463     }
3464 }
3465
3466 const char *
3467 requestToString(int request) {
3468 /*
3469  cat libs/telephony/ril_commands.h \
3470  | egrep "^ *{RIL_" \
3471  | sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
3472
3473
3474  cat libs/telephony/ril_unsol_commands.h \
3475  | egrep "^ *{RIL_" \
3476  | sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
3477
3478 */
3479     switch(request) {
3480         case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
3481         case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
3482         case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
3483         case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
3484         case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
3485         case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
3486         case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
3487         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
3488         case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
3489         case RIL_REQUEST_DIAL: return "DIAL";
3490         case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
3491         case RIL_REQUEST_HANGUP: return "HANGUP";
3492         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
3493         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
3494         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
3495         case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
3496         case RIL_REQUEST_UDUB: return "UDUB";
3497         case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
3498         case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
3499         case RIL_REQUEST_VOICE_REGISTRATION_STATE: return "VOICE_REGISTRATION_STATE";
3500         case RIL_REQUEST_DATA_REGISTRATION_STATE: return "DATA_REGISTRATION_STATE";
3501         case RIL_REQUEST_OPERATOR: return "OPERATOR";
3502         case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
3503         case RIL_REQUEST_DTMF: return "DTMF";
3504         case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
3505         case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
3506         case RIL_REQUEST_SETUP_DATA_CALL: return "SETUP_DATA_CALL";
3507         case RIL_REQUEST_SIM_IO: return "SIM_IO";
3508         case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
3509         case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
3510         case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
3511         case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
3512         case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
3513         case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
3514         case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
3515         case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
3516         case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
3517         case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
3518         case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
3519         case RIL_REQUEST_ANSWER: return "ANSWER";
3520         case RIL_REQUEST_DEACTIVATE_DATA_CALL: return "DEACTIVATE_DATA_CALL";
3521         case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
3522         case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
3523         case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
3524         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
3525         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
3526         case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
3527         case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
3528         case RIL_REQUEST_DTMF_START: return "DTMF_START";
3529         case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
3530         case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
3531         case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
3532         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
3533         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
3534         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
3535         case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
3536         case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
3537         case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
3538         case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: return "LAST_DATA_CALL_FAIL_CAUSE";
3539         case RIL_REQUEST_DATA_CALL_LIST: return "DATA_CALL_LIST";
3540         case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
3541         case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
3542         case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
3543         case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
3544         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
3545         case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
3546         case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
3547         case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
3548         case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
3549         case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
3550         case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
3551         case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
3552         case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
3553         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:return"CDMA_SET_SUBSCRIPTION_SOURCE";
3554         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:return"CDMA_SET_ROAMING_PREFERENCE";
3555         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:return"CDMA_QUERY_ROAMING_PREFERENCE";
3556         case RIL_REQUEST_SET_TTY_MODE:return"SET_TTY_MODE";
3557         case RIL_REQUEST_QUERY_TTY_MODE:return"QUERY_TTY_MODE";
3558         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE";
3559         case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE";
3560         case RIL_REQUEST_CDMA_FLASH:return"CDMA_FLASH";
3561         case RIL_REQUEST_CDMA_BURST_DTMF:return"CDMA_BURST_DTMF";
3562         case RIL_REQUEST_CDMA_SEND_SMS:return"CDMA_SEND_SMS";
3563         case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:return"CDMA_SMS_ACKNOWLEDGE";
3564         case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:return"GSM_GET_BROADCAST_SMS_CONFIG";
3565         case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:return"GSM_SET_BROADCAST_SMS_CONFIG";
3566         case RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG:return "CDMA_GET_BROADCAST_SMS_CONFIG";
3567         case RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG:return "CDMA_SET_BROADCAST_SMS_CONFIG";
3568         case RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION:return "CDMA_SMS_BROADCAST_ACTIVATION";
3569         case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: return"CDMA_VALIDATE_AND_WRITE_AKEY";
3570         case RIL_REQUEST_CDMA_SUBSCRIPTION: return"CDMA_SUBSCRIPTION";
3571         case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: return "CDMA_WRITE_SMS_TO_RUIM";
3572         case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: return "CDMA_DELETE_SMS_ON_RUIM";
3573         case RIL_REQUEST_DEVICE_IDENTITY: return "DEVICE_IDENTITY";
3574         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: return "EXIT_EMERGENCY_CALLBACK_MODE";
3575         case RIL_REQUEST_GET_SMSC_ADDRESS: return "GET_SMSC_ADDRESS";
3576         case RIL_REQUEST_SET_SMSC_ADDRESS: return "SET_SMSC_ADDRESS";
3577         case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: return "REPORT_SMS_MEMORY_STATUS";
3578         case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: return "REPORT_STK_SERVICE_IS_RUNNING";
3579         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE: return "CDMA_GET_SUBSCRIPTION_SOURCE";
3580         case RIL_REQUEST_ISIM_AUTHENTICATION: return "ISIM_AUTHENTICATION";
3581         case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: return "RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU";
3582         case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: return "RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS";
3583         case RIL_REQUEST_VOICE_RADIO_TECH: return "VOICE_RADIO_TECH";
3584         case RIL_REQUEST_GET_CELL_INFO_LIST: return"GET_CELL_INFO_LIST";
3585         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE: return"SET_UNSOL_CELL_INFO_LIST_RATE";
3586         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
3587         case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
3588         case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED";
3589         case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
3590         case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
3591         case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
3592         case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
3593         case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
3594         case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
3595         case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
3596         case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
3597         case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
3598         case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
3599         case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
3600         case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
3601         case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
3602         case RIL_UNSOL_DATA_CALL_LIST_CHANGED: return "UNSOL_DATA_CALL_LIST_CHANGED";
3603         case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
3604         case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED: return "UNSOL_RESPONSE_SIM_STATUS_CHANGED";
3605         case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS: return "UNSOL_NEW_CDMA_SMS";
3606         case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS: return "UNSOL_NEW_BROADCAST_SMS";
3607         case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL: return "UNSOL_CDMA_RUIM_SMS_STORAGE_FULL";
3608         case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "UNSOL_RESTRICTED_STATE_CHANGED";
3609         case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE: return "UNSOL_ENTER_EMERGENCY_CALLBACK_MODE";
3610         case RIL_UNSOL_CDMA_CALL_WAITING: return "UNSOL_CDMA_CALL_WAITING";
3611         case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS: return "UNSOL_CDMA_OTA_PROVISION_STATUS";
3612         case RIL_UNSOL_CDMA_INFO_REC: return "UNSOL_CDMA_INFO_REC";
3613         case RIL_UNSOL_OEM_HOOK_RAW: return "UNSOL_OEM_HOOK_RAW";
3614         case RIL_UNSOL_RINGBACK_TONE: return "UNSOL_RINGBACK_TONE";
3615         case RIL_UNSOL_RESEND_INCALL_MUTE: return "UNSOL_RESEND_INCALL_MUTE";
3616         case RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED: return "UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED";
3617         case RIL_UNSOL_CDMA_PRL_CHANGED: return "UNSOL_CDMA_PRL_CHANGED";
3618         case RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE: return "UNSOL_EXIT_EMERGENCY_CALLBACK_MODE";
3619         case RIL_UNSOL_RIL_CONNECTED: return "UNSOL_RIL_CONNECTED";
3620         case RIL_UNSOL_VOICE_RADIO_TECH_CHANGED: return "UNSOL_VOICE_RADIO_TECH_CHANGED";
3621         case RIL_UNSOL_CELL_INFO_LIST: return "UNSOL_CELL_INFO_LIST";
3622         default: return "<unknown request>";
3623     }
3624 }
3625
3626 } /* namespace android */