OSDN Git Service

Add CellInfoWcdma.
[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,", 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                 appendPrintBuf("%s gsmSS: ss=%d,ber=%d],", printBuf,
2223                     p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength,
2224                     p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
2225
2226                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
2227                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
2228                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
2229                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
2230                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
2231                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
2232                 break;
2233             }
2234             case RIL_CELL_INFO_TYPE_WCDMA: {
2235                 appendPrintBuf("%s WCDMA id: mcc=%d,mnc=%d,lac=%d,cid=%d,psc=%d,", printBuf,
2236                     p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc,
2237                     p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc,
2238                     p_cur->CellInfo.wcdma.cellIdentityWcdma.lac,
2239                     p_cur->CellInfo.wcdma.cellIdentityWcdma.cid,
2240                     p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
2241                 appendPrintBuf("%s wcdmaSS: ss=%d,ber=%d],", printBuf,
2242                     p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength,
2243                     p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
2244
2245                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc);
2246                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc);
2247                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.lac);
2248                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.cid);
2249                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
2250                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
2251                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
2252                 break;
2253             }
2254             case RIL_CELL_INFO_TYPE_CDMA: {
2255                 appendPrintBuf("%s CDMA id: nId=%d,sId=%d,bsId=%d,long=%d,lat=%d", printBuf,
2256                     p_cur->CellInfo.cdma.cellIdentityCdma.networkId,
2257                     p_cur->CellInfo.cdma.cellIdentityCdma.systemId,
2258                     p_cur->CellInfo.cdma.cellIdentityCdma.basestationId,
2259                     p_cur->CellInfo.cdma.cellIdentityCdma.longitude,
2260                     p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
2261
2262                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
2263                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
2264                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
2265                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
2266                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
2267
2268                 appendPrintBuf("%s cdmaSS: dbm=%d ecio=%d evdoSS: dbm=%d,ecio=%d,snr=%d", printBuf,
2269                     p_cur->CellInfo.cdma.signalStrengthCdma.dbm,
2270                     p_cur->CellInfo.cdma.signalStrengthCdma.ecio,
2271                     p_cur->CellInfo.cdma.signalStrengthEvdo.dbm,
2272                     p_cur->CellInfo.cdma.signalStrengthEvdo.ecio,
2273                     p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
2274
2275                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
2276                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
2277                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
2278                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
2279                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
2280                 break;
2281             }
2282             case RIL_CELL_INFO_TYPE_LTE: {
2283                 appendPrintBuf("%s LTE id: mcc=%d,mnc=%d,ci=%d,pci=%d,tac=%d", printBuf,
2284                     p_cur->CellInfo.lte.cellIdentityLte.mcc,
2285                     p_cur->CellInfo.lte.cellIdentityLte.mnc,
2286                     p_cur->CellInfo.lte.cellIdentityLte.ci,
2287                     p_cur->CellInfo.lte.cellIdentityLte.pci,
2288                     p_cur->CellInfo.lte.cellIdentityLte.tac);
2289
2290                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
2291                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
2292                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
2293                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
2294                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
2295
2296                 appendPrintBuf("%s lteSS: ss=%d,rsrp=%d,rsrq=%d,rssnr=%d,cqi=%d,ta=%d", printBuf,
2297                     p_cur->CellInfo.lte.signalStrengthLte.signalStrength,
2298                     p_cur->CellInfo.lte.signalStrengthLte.rsrp,
2299                     p_cur->CellInfo.lte.signalStrengthLte.rsrq,
2300                     p_cur->CellInfo.lte.signalStrengthLte.rssnr,
2301                     p_cur->CellInfo.lte.signalStrengthLte.cqi,
2302                     p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
2303                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
2304                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
2305                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
2306                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
2307                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
2308                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
2309                 break;
2310             }
2311         }
2312         p_cur += 1;
2313     }
2314     removeLastChar;
2315     closeResponse;
2316
2317     return 0;
2318 }
2319
2320 static void triggerEvLoop() {
2321     int ret;
2322     if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
2323         /* trigger event loop to wakeup. No reason to do this,
2324          * if we're in the event loop thread */
2325          do {
2326             ret = write (s_fdWakeupWrite, " ", 1);
2327          } while (ret < 0 && errno == EINTR);
2328     }
2329 }
2330
2331 static void rilEventAddWakeup(struct ril_event *ev) {
2332     ril_event_add(ev);
2333     triggerEvLoop();
2334 }
2335
2336 static void sendSimStatusAppInfo(Parcel &p, int num_apps, RIL_AppStatus appStatus[]) {
2337         p.writeInt32(num_apps);
2338         startResponse;
2339         for (int i = 0; i < num_apps; i++) {
2340             p.writeInt32(appStatus[i].app_type);
2341             p.writeInt32(appStatus[i].app_state);
2342             p.writeInt32(appStatus[i].perso_substate);
2343             writeStringToParcel(p, (const char*)(appStatus[i].aid_ptr));
2344             writeStringToParcel(p, (const char*)
2345                                           (appStatus[i].app_label_ptr));
2346             p.writeInt32(appStatus[i].pin1_replaced);
2347             p.writeInt32(appStatus[i].pin1);
2348             p.writeInt32(appStatus[i].pin2);
2349             appendPrintBuf("%s[app_type=%d,app_state=%d,perso_substate=%d,\
2350                     aid_ptr=%s,app_label_ptr=%s,pin1_replaced=%d,pin1=%d,pin2=%d],",
2351                     printBuf,
2352                     appStatus[i].app_type,
2353                     appStatus[i].app_state,
2354                     appStatus[i].perso_substate,
2355                     appStatus[i].aid_ptr,
2356                     appStatus[i].app_label_ptr,
2357                     appStatus[i].pin1_replaced,
2358                     appStatus[i].pin1,
2359                     appStatus[i].pin2);
2360         }
2361         closeResponse;
2362 }
2363
2364 static int responseSimStatus(Parcel &p, void *response, size_t responselen) {
2365     int i;
2366
2367     if (response == NULL && responselen != 0) {
2368         RLOGE("invalid response: NULL");
2369         return RIL_ERRNO_INVALID_RESPONSE;
2370     }
2371
2372     if (responselen == sizeof (RIL_CardStatus_v6)) {
2373         RIL_CardStatus_v6 *p_cur = ((RIL_CardStatus_v6 *) response);
2374
2375         p.writeInt32(p_cur->card_state);
2376         p.writeInt32(p_cur->universal_pin_state);
2377         p.writeInt32(p_cur->gsm_umts_subscription_app_index);
2378         p.writeInt32(p_cur->cdma_subscription_app_index);
2379         p.writeInt32(p_cur->ims_subscription_app_index);
2380
2381         sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
2382     } else if (responselen == sizeof (RIL_CardStatus_v5)) {
2383         RIL_CardStatus_v5 *p_cur = ((RIL_CardStatus_v5 *) response);
2384
2385         p.writeInt32(p_cur->card_state);
2386         p.writeInt32(p_cur->universal_pin_state);
2387         p.writeInt32(p_cur->gsm_umts_subscription_app_index);
2388         p.writeInt32(p_cur->cdma_subscription_app_index);
2389         p.writeInt32(-1);
2390
2391         sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
2392     } else {
2393         RLOGE("responseSimStatus: A RilCardStatus_v6 or _v5 expected\n");
2394         return RIL_ERRNO_INVALID_RESPONSE;
2395     }
2396
2397     return 0;
2398 }
2399
2400 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2401     int num = responselen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
2402     p.writeInt32(num);
2403
2404     startResponse;
2405     RIL_GSM_BroadcastSmsConfigInfo **p_cur =
2406                 (RIL_GSM_BroadcastSmsConfigInfo **) response;
2407     for (int i = 0; i < num; i++) {
2408         p.writeInt32(p_cur[i]->fromServiceId);
2409         p.writeInt32(p_cur[i]->toServiceId);
2410         p.writeInt32(p_cur[i]->fromCodeScheme);
2411         p.writeInt32(p_cur[i]->toCodeScheme);
2412         p.writeInt32(p_cur[i]->selected);
2413
2414         appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId=%d, \
2415                 fromCodeScheme=%d, toCodeScheme=%d, selected =%d]",
2416                 printBuf, i, p_cur[i]->fromServiceId, p_cur[i]->toServiceId,
2417                 p_cur[i]->fromCodeScheme, p_cur[i]->toCodeScheme,
2418                 p_cur[i]->selected);
2419     }
2420     closeResponse;
2421
2422     return 0;
2423 }
2424
2425 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2426     RIL_CDMA_BroadcastSmsConfigInfo **p_cur =
2427                (RIL_CDMA_BroadcastSmsConfigInfo **) response;
2428
2429     int num = responselen / sizeof (RIL_CDMA_BroadcastSmsConfigInfo *);
2430     p.writeInt32(num);
2431
2432     startResponse;
2433     for (int i = 0 ; i < num ; i++ ) {
2434         p.writeInt32(p_cur[i]->service_category);
2435         p.writeInt32(p_cur[i]->language);
2436         p.writeInt32(p_cur[i]->selected);
2437
2438         appendPrintBuf("%s [%d: srvice_category=%d, language =%d, \
2439               selected =%d], ",
2440               printBuf, i, p_cur[i]->service_category, p_cur[i]->language,
2441               p_cur[i]->selected);
2442     }
2443     closeResponse;
2444
2445     return 0;
2446 }
2447
2448 static int responseCdmaSms(Parcel &p, void *response, size_t responselen) {
2449     int num;
2450     int digitCount;
2451     int digitLimit;
2452     uint8_t uct;
2453     void* dest;
2454
2455     RLOGD("Inside responseCdmaSms");
2456
2457     if (response == NULL && responselen != 0) {
2458         RLOGE("invalid response: NULL");
2459         return RIL_ERRNO_INVALID_RESPONSE;
2460     }
2461
2462     if (responselen != sizeof(RIL_CDMA_SMS_Message)) {
2463         RLOGE("invalid response length was %d expected %d",
2464                 (int)responselen, (int)sizeof(RIL_CDMA_SMS_Message));
2465         return RIL_ERRNO_INVALID_RESPONSE;
2466     }
2467
2468     RIL_CDMA_SMS_Message *p_cur = (RIL_CDMA_SMS_Message *) response;
2469     p.writeInt32(p_cur->uTeleserviceID);
2470     p.write(&(p_cur->bIsServicePresent),sizeof(uct));
2471     p.writeInt32(p_cur->uServicecategory);
2472     p.writeInt32(p_cur->sAddress.digit_mode);
2473     p.writeInt32(p_cur->sAddress.number_mode);
2474     p.writeInt32(p_cur->sAddress.number_type);
2475     p.writeInt32(p_cur->sAddress.number_plan);
2476     p.write(&(p_cur->sAddress.number_of_digits), sizeof(uct));
2477     digitLimit= MIN((p_cur->sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
2478     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2479         p.write(&(p_cur->sAddress.digits[digitCount]),sizeof(uct));
2480     }
2481
2482     p.writeInt32(p_cur->sSubAddress.subaddressType);
2483     p.write(&(p_cur->sSubAddress.odd),sizeof(uct));
2484     p.write(&(p_cur->sSubAddress.number_of_digits),sizeof(uct));
2485     digitLimit= MIN((p_cur->sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
2486     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2487         p.write(&(p_cur->sSubAddress.digits[digitCount]),sizeof(uct));
2488     }
2489
2490     digitLimit= MIN((p_cur->uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
2491     p.writeInt32(p_cur->uBearerDataLen);
2492     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2493        p.write(&(p_cur->aBearerData[digitCount]), sizeof(uct));
2494     }
2495
2496     startResponse;
2497     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
2498             sAddress.digit_mode=%d, sAddress.number_mode=%d, sAddress.number_type=%d, ",
2499             printBuf, p_cur->uTeleserviceID,p_cur->bIsServicePresent,p_cur->uServicecategory,
2500             p_cur->sAddress.digit_mode, p_cur->sAddress.number_mode,p_cur->sAddress.number_type);
2501     closeResponse;
2502
2503     return 0;
2504 }
2505
2506 /**
2507  * A write on the wakeup fd is done just to pop us out of select()
2508  * We empty the buffer here and then ril_event will reset the timers on the
2509  * way back down
2510  */
2511 static void processWakeupCallback(int fd, short flags, void *param) {
2512     char buff[16];
2513     int ret;
2514
2515     RLOGV("processWakeupCallback");
2516
2517     /* empty our wakeup socket out */
2518     do {
2519         ret = read(s_fdWakeupRead, &buff, sizeof(buff));
2520     } while (ret > 0 || (ret < 0 && errno == EINTR));
2521 }
2522
2523 static void onCommandsSocketClosed() {
2524     int ret;
2525     RequestInfo *p_cur;
2526
2527     /* mark pending requests as "cancelled" so we dont report responses */
2528
2529     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
2530     assert (ret == 0);
2531
2532     p_cur = s_pendingRequests;
2533
2534     for (p_cur = s_pendingRequests
2535             ; p_cur != NULL
2536             ; p_cur  = p_cur->p_next
2537     ) {
2538         p_cur->cancelled = 1;
2539     }
2540
2541     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
2542     assert (ret == 0);
2543 }
2544
2545 static void processCommandsCallback(int fd, short flags, void *param) {
2546     RecordStream *p_rs;
2547     void *p_record;
2548     size_t recordlen;
2549     int ret;
2550
2551     assert(fd == s_fdCommand);
2552
2553     p_rs = (RecordStream *)param;
2554
2555     for (;;) {
2556         /* loop until EAGAIN/EINTR, end of stream, or other error */
2557         ret = record_stream_get_next(p_rs, &p_record, &recordlen);
2558
2559         if (ret == 0 && p_record == NULL) {
2560             /* end-of-stream */
2561             break;
2562         } else if (ret < 0) {
2563             break;
2564         } else if (ret == 0) { /* && p_record != NULL */
2565             processCommandBuffer(p_record, recordlen);
2566         }
2567     }
2568
2569     if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
2570         /* fatal error or end-of-stream */
2571         if (ret != 0) {
2572             RLOGE("error on reading command socket errno:%d\n", errno);
2573         } else {
2574             RLOGW("EOS.  Closing command socket.");
2575         }
2576
2577         close(s_fdCommand);
2578         s_fdCommand = -1;
2579
2580         ril_event_del(&s_commands_event);
2581
2582         record_stream_free(p_rs);
2583
2584         /* start listening for new connections again */
2585         rilEventAddWakeup(&s_listen_event);
2586
2587         onCommandsSocketClosed();
2588     }
2589 }
2590
2591
2592 static void onNewCommandConnect() {
2593     // Inform we are connected and the ril version
2594     int rilVer = s_callbacks.version;
2595     RIL_onUnsolicitedResponse(RIL_UNSOL_RIL_CONNECTED,
2596                                     &rilVer, sizeof(rilVer));
2597
2598     // implicit radio state changed
2599     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
2600                                     NULL, 0);
2601
2602     // Send last NITZ time data, in case it was missed
2603     if (s_lastNITZTimeData != NULL) {
2604         sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize);
2605
2606         free(s_lastNITZTimeData);
2607         s_lastNITZTimeData = NULL;
2608     }
2609
2610     // Get version string
2611     if (s_callbacks.getVersion != NULL) {
2612         const char *version;
2613         version = s_callbacks.getVersion();
2614         RLOGI("RIL Daemon version: %s\n", version);
2615
2616         property_set(PROPERTY_RIL_IMPL, version);
2617     } else {
2618         RLOGI("RIL Daemon version: unavailable\n");
2619         property_set(PROPERTY_RIL_IMPL, "unavailable");
2620     }
2621
2622 }
2623
2624 static void listenCallback (int fd, short flags, void *param) {
2625     int ret;
2626     int err;
2627     int is_phone_socket;
2628     RecordStream *p_rs;
2629
2630     struct sockaddr_un peeraddr;
2631     socklen_t socklen = sizeof (peeraddr);
2632
2633     struct ucred creds;
2634     socklen_t szCreds = sizeof(creds);
2635
2636     struct passwd *pwd = NULL;
2637
2638     assert (s_fdCommand < 0);
2639     assert (fd == s_fdListen);
2640
2641     s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen);
2642
2643     if (s_fdCommand < 0 ) {
2644         RLOGE("Error on accept() errno:%d", errno);
2645         /* start listening for new connections again */
2646         rilEventAddWakeup(&s_listen_event);
2647               return;
2648     }
2649
2650     /* check the credential of the other side and only accept socket from
2651      * phone process
2652      */
2653     errno = 0;
2654     is_phone_socket = 0;
2655
2656     err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
2657
2658     if (err == 0 && szCreds > 0) {
2659         errno = 0;
2660         pwd = getpwuid(creds.uid);
2661         if (pwd != NULL) {
2662             if (strcmp(pwd->pw_name, PHONE_PROCESS) == 0) {
2663                 is_phone_socket = 1;
2664             } else {
2665                 RLOGE("RILD can't accept socket from process %s", pwd->pw_name);
2666             }
2667         } else {
2668             RLOGE("Error on getpwuid() errno: %d", errno);
2669         }
2670     } else {
2671         RLOGD("Error on getsockopt() errno: %d", errno);
2672     }
2673
2674     if ( !is_phone_socket ) {
2675       RLOGE("RILD must accept socket from %s", PHONE_PROCESS);
2676
2677       close(s_fdCommand);
2678       s_fdCommand = -1;
2679
2680       onCommandsSocketClosed();
2681
2682       /* start listening for new connections again */
2683       rilEventAddWakeup(&s_listen_event);
2684
2685       return;
2686     }
2687
2688     ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK);
2689
2690     if (ret < 0) {
2691         RLOGE ("Error setting O_NONBLOCK errno:%d", errno);
2692     }
2693
2694     RLOGI("libril: new connection");
2695
2696     p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES);
2697
2698     ril_event_set (&s_commands_event, s_fdCommand, 1,
2699         processCommandsCallback, p_rs);
2700
2701     rilEventAddWakeup (&s_commands_event);
2702
2703     onNewCommandConnect();
2704 }
2705
2706 static void freeDebugCallbackArgs(int number, char **args) {
2707     for (int i = 0; i < number; i++) {
2708         if (args[i] != NULL) {
2709             free(args[i]);
2710         }
2711     }
2712     free(args);
2713 }
2714
2715 static void debugCallback (int fd, short flags, void *param) {
2716     int acceptFD, option;
2717     struct sockaddr_un peeraddr;
2718     socklen_t socklen = sizeof (peeraddr);
2719     int data;
2720     unsigned int qxdm_data[6];
2721     const char *deactData[1] = {"1"};
2722     char *actData[1];
2723     RIL_Dial dialData;
2724     int hangupData[1] = {1};
2725     int number;
2726     char **args;
2727
2728     acceptFD = accept (fd,  (sockaddr *) &peeraddr, &socklen);
2729
2730     if (acceptFD < 0) {
2731         RLOGE ("error accepting on debug port: %d\n", errno);
2732         return;
2733     }
2734
2735     if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
2736         RLOGE ("error reading on socket: number of Args: \n");
2737         return;
2738     }
2739     args = (char **) malloc(sizeof(char*) * number);
2740
2741     for (int i = 0; i < number; i++) {
2742         int len;
2743         if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
2744             RLOGE ("error reading on socket: Len of Args: \n");
2745             freeDebugCallbackArgs(i, args);
2746             return;
2747         }
2748         // +1 for null-term
2749         args[i] = (char *) malloc((sizeof(char) * len) + 1);
2750         if (recv(acceptFD, args[i], sizeof(char) * len, 0)
2751             != (int)sizeof(char) * len) {
2752             RLOGE ("error reading on socket: Args[%d] \n", i);
2753             freeDebugCallbackArgs(i, args);
2754             return;
2755         }
2756         char * buf = args[i];
2757         buf[len] = 0;
2758     }
2759
2760     switch (atoi(args[0])) {
2761         case 0:
2762             RLOGI ("Connection on debug port: issuing reset.");
2763             issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0);
2764             break;
2765         case 1:
2766             RLOGI ("Connection on debug port: issuing radio power off.");
2767             data = 0;
2768             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2769             // Close the socket
2770             close(s_fdCommand);
2771             s_fdCommand = -1;
2772             break;
2773         case 2:
2774             RLOGI ("Debug port: issuing unsolicited voice network change.");
2775             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
2776                                       NULL, 0);
2777             break;
2778         case 3:
2779             RLOGI ("Debug port: QXDM log enable.");
2780             qxdm_data[0] = 65536;     // head.func_tag
2781             qxdm_data[1] = 16;        // head.len
2782             qxdm_data[2] = 1;         // mode: 1 for 'start logging'
2783             qxdm_data[3] = 32;        // log_file_size: 32megabytes
2784             qxdm_data[4] = 0;         // log_mask
2785             qxdm_data[5] = 8;         // log_max_fileindex
2786             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2787                               6 * sizeof(int));
2788             break;
2789         case 4:
2790             RLOGI ("Debug port: QXDM log disable.");
2791             qxdm_data[0] = 65536;
2792             qxdm_data[1] = 16;
2793             qxdm_data[2] = 0;          // mode: 0 for 'stop logging'
2794             qxdm_data[3] = 32;
2795             qxdm_data[4] = 0;
2796             qxdm_data[5] = 8;
2797             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2798                               6 * sizeof(int));
2799             break;
2800         case 5:
2801             RLOGI("Debug port: Radio On");
2802             data = 1;
2803             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2804             sleep(2);
2805             // Set network selection automatic.
2806             issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0);
2807             break;
2808         case 6:
2809             RLOGI("Debug port: Setup Data Call, Apn :%s\n", args[1]);
2810             actData[0] = args[1];
2811             issueLocalRequest(RIL_REQUEST_SETUP_DATA_CALL, &actData,
2812                               sizeof(actData));
2813             break;
2814         case 7:
2815             RLOGI("Debug port: Deactivate Data Call");
2816             issueLocalRequest(RIL_REQUEST_DEACTIVATE_DATA_CALL, &deactData,
2817                               sizeof(deactData));
2818             break;
2819         case 8:
2820             RLOGI("Debug port: Dial Call");
2821             dialData.clir = 0;
2822             dialData.address = args[1];
2823             issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData));
2824             break;
2825         case 9:
2826             RLOGI("Debug port: Answer Call");
2827             issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0);
2828             break;
2829         case 10:
2830             RLOGI("Debug port: End Call");
2831             issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
2832                               sizeof(hangupData));
2833             break;
2834         default:
2835             RLOGE ("Invalid request");
2836             break;
2837     }
2838     freeDebugCallbackArgs(number, args);
2839     close(acceptFD);
2840 }
2841
2842
2843 static void userTimerCallback (int fd, short flags, void *param) {
2844     UserCallbackInfo *p_info;
2845
2846     p_info = (UserCallbackInfo *)param;
2847
2848     p_info->p_callback(p_info->userParam);
2849
2850
2851     // FIXME generalize this...there should be a cancel mechanism
2852     if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
2853         s_last_wake_timeout_info = NULL;
2854     }
2855
2856     free(p_info);
2857 }
2858
2859
2860 static void *
2861 eventLoop(void *param) {
2862     int ret;
2863     int filedes[2];
2864
2865     ril_event_init();
2866
2867     pthread_mutex_lock(&s_startupMutex);
2868
2869     s_started = 1;
2870     pthread_cond_broadcast(&s_startupCond);
2871
2872     pthread_mutex_unlock(&s_startupMutex);
2873
2874     ret = pipe(filedes);
2875
2876     if (ret < 0) {
2877         RLOGE("Error in pipe() errno:%d", errno);
2878         return NULL;
2879     }
2880
2881     s_fdWakeupRead = filedes[0];
2882     s_fdWakeupWrite = filedes[1];
2883
2884     fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
2885
2886     ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
2887                 processWakeupCallback, NULL);
2888
2889     rilEventAddWakeup (&s_wakeupfd_event);
2890
2891     // Only returns on error
2892     ril_event_loop();
2893     RLOGE ("error in event_loop_base errno:%d", errno);
2894     // kill self to restart on error
2895     kill(0, SIGKILL);
2896
2897     return NULL;
2898 }
2899
2900 extern "C" void
2901 RIL_startEventLoop(void) {
2902     int ret;
2903     pthread_attr_t attr;
2904
2905     /* spin up eventLoop thread and wait for it to get started */
2906     s_started = 0;
2907     pthread_mutex_lock(&s_startupMutex);
2908
2909     pthread_attr_init (&attr);
2910     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2911     ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
2912
2913     while (s_started == 0) {
2914         pthread_cond_wait(&s_startupCond, &s_startupMutex);
2915     }
2916
2917     pthread_mutex_unlock(&s_startupMutex);
2918
2919     if (ret < 0) {
2920         RLOGE("Failed to create dispatch thread errno:%d", errno);
2921         return;
2922     }
2923 }
2924
2925 // Used for testing purpose only.
2926 extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
2927     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
2928 }
2929
2930 extern "C" void
2931 RIL_register (const RIL_RadioFunctions *callbacks) {
2932     int ret;
2933     int flags;
2934
2935     if (callbacks == NULL) {
2936         RLOGE("RIL_register: RIL_RadioFunctions * null");
2937         return;
2938     }
2939     if (callbacks->version < RIL_VERSION_MIN) {
2940         RLOGE("RIL_register: version %d is to old, min version is %d",
2941              callbacks->version, RIL_VERSION_MIN);
2942         return;
2943     }
2944     if (callbacks->version > RIL_VERSION) {
2945         RLOGE("RIL_register: version %d is too new, max version is %d",
2946              callbacks->version, RIL_VERSION);
2947         return;
2948     }
2949     RLOGE("RIL_register: RIL version %d", callbacks->version);
2950
2951     if (s_registerCalled > 0) {
2952         RLOGE("RIL_register has been called more than once. "
2953                 "Subsequent call ignored");
2954         return;
2955     }
2956
2957     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
2958
2959     s_registerCalled = 1;
2960
2961     // Little self-check
2962
2963     for (int i = 0; i < (int)NUM_ELEMS(s_commands); i++) {
2964         assert(i == s_commands[i].requestNumber);
2965     }
2966
2967     for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses); i++) {
2968         assert(i + RIL_UNSOL_RESPONSE_BASE
2969                 == s_unsolResponses[i].requestNumber);
2970     }
2971
2972     // New rild impl calls RIL_startEventLoop() first
2973     // old standalone impl wants it here.
2974
2975     if (s_started == 0) {
2976         RIL_startEventLoop();
2977     }
2978
2979     // start listen socket
2980
2981 #if 0
2982     ret = socket_local_server (SOCKET_NAME_RIL,
2983             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
2984
2985     if (ret < 0) {
2986         RLOGE("Unable to bind socket errno:%d", errno);
2987         exit (-1);
2988     }
2989     s_fdListen = ret;
2990
2991 #else
2992     s_fdListen = android_get_control_socket(SOCKET_NAME_RIL);
2993     if (s_fdListen < 0) {
2994         RLOGE("Failed to get socket '" SOCKET_NAME_RIL "'");
2995         exit(-1);
2996     }
2997
2998     ret = listen(s_fdListen, 4);
2999
3000     if (ret < 0) {
3001         RLOGE("Failed to listen on control socket '%d': %s",
3002              s_fdListen, strerror(errno));
3003         exit(-1);
3004     }
3005 #endif
3006
3007
3008     /* note: non-persistent so we can accept only one connection at a time */
3009     ril_event_set (&s_listen_event, s_fdListen, false,
3010                 listenCallback, NULL);
3011
3012     rilEventAddWakeup (&s_listen_event);
3013
3014 #if 1
3015     // start debug interface socket
3016
3017     s_fdDebug = android_get_control_socket(SOCKET_NAME_RIL_DEBUG);
3018     if (s_fdDebug < 0) {
3019         RLOGE("Failed to get socket '" SOCKET_NAME_RIL_DEBUG "' errno:%d", errno);
3020         exit(-1);
3021     }
3022
3023     ret = listen(s_fdDebug, 4);
3024
3025     if (ret < 0) {
3026         RLOGE("Failed to listen on ril debug socket '%d': %s",
3027              s_fdDebug, strerror(errno));
3028         exit(-1);
3029     }
3030
3031     ril_event_set (&s_debug_event, s_fdDebug, true,
3032                 debugCallback, NULL);
3033
3034     rilEventAddWakeup (&s_debug_event);
3035 #endif
3036
3037 }
3038
3039 static int
3040 checkAndDequeueRequestInfo(struct RequestInfo *pRI) {
3041     int ret = 0;
3042
3043     if (pRI == NULL) {
3044         return 0;
3045     }
3046
3047     pthread_mutex_lock(&s_pendingRequestsMutex);
3048
3049     for(RequestInfo **ppCur = &s_pendingRequests
3050         ; *ppCur != NULL
3051         ; ppCur = &((*ppCur)->p_next)
3052     ) {
3053         if (pRI == *ppCur) {
3054             ret = 1;
3055
3056             *ppCur = (*ppCur)->p_next;
3057             break;
3058         }
3059     }
3060
3061     pthread_mutex_unlock(&s_pendingRequestsMutex);
3062
3063     return ret;
3064 }
3065
3066
3067 extern "C" void
3068 RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen) {
3069     RequestInfo *pRI;
3070     int ret;
3071     size_t errorOffset;
3072
3073     pRI = (RequestInfo *)t;
3074
3075     if (!checkAndDequeueRequestInfo(pRI)) {
3076         RLOGE ("RIL_onRequestComplete: invalid RIL_Token");
3077         return;
3078     }
3079
3080     if (pRI->local > 0) {
3081         // Locally issued command...void only!
3082         // response does not go back up the command socket
3083         RLOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
3084
3085         goto done;
3086     }
3087
3088     appendPrintBuf("[%04d]< %s",
3089         pRI->token, requestToString(pRI->pCI->requestNumber));
3090
3091     if (pRI->cancelled == 0) {
3092         Parcel p;
3093
3094         p.writeInt32 (RESPONSE_SOLICITED);
3095         p.writeInt32 (pRI->token);
3096         errorOffset = p.dataPosition();
3097
3098         p.writeInt32 (e);
3099
3100         if (response != NULL) {
3101             // there is a response payload, no matter success or not.
3102             ret = pRI->pCI->responseFunction(p, response, responselen);
3103
3104             /* if an error occurred, rewind and mark it */
3105             if (ret != 0) {
3106                 p.setDataPosition(errorOffset);
3107                 p.writeInt32 (ret);
3108             }
3109         }
3110
3111         if (e != RIL_E_SUCCESS) {
3112             appendPrintBuf("%s fails by %s", printBuf, failCauseToString(e));
3113         }
3114
3115         if (s_fdCommand < 0) {
3116             RLOGD ("RIL onRequestComplete: Command channel closed");
3117         }
3118         sendResponse(p);
3119     }
3120
3121 done:
3122     free(pRI);
3123 }
3124
3125
3126 static void
3127 grabPartialWakeLock() {
3128     acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
3129 }
3130
3131 static void
3132 releaseWakeLock() {
3133     release_wake_lock(ANDROID_WAKE_LOCK_NAME);
3134 }
3135
3136 /**
3137  * Timer callback to put us back to sleep before the default timeout
3138  */
3139 static void
3140 wakeTimeoutCallback (void *param) {
3141     // We're using "param != NULL" as a cancellation mechanism
3142     if (param == NULL) {
3143         //RLOGD("wakeTimeout: releasing wake lock");
3144
3145         releaseWakeLock();
3146     } else {
3147         //RLOGD("wakeTimeout: releasing wake lock CANCELLED");
3148     }
3149 }
3150
3151 static int
3152 decodeVoiceRadioTechnology (RIL_RadioState radioState) {
3153     switch (radioState) {
3154         case RADIO_STATE_SIM_NOT_READY:
3155         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3156         case RADIO_STATE_SIM_READY:
3157             return RADIO_TECH_UMTS;
3158
3159         case RADIO_STATE_RUIM_NOT_READY:
3160         case RADIO_STATE_RUIM_READY:
3161         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3162         case RADIO_STATE_NV_NOT_READY:
3163         case RADIO_STATE_NV_READY:
3164             return RADIO_TECH_1xRTT;
3165
3166         default:
3167             RLOGD("decodeVoiceRadioTechnology: Invoked with incorrect RadioState");
3168             return -1;
3169     }
3170 }
3171
3172 static int
3173 decodeCdmaSubscriptionSource (RIL_RadioState radioState) {
3174     switch (radioState) {
3175         case RADIO_STATE_SIM_NOT_READY:
3176         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3177         case RADIO_STATE_SIM_READY:
3178         case RADIO_STATE_RUIM_NOT_READY:
3179         case RADIO_STATE_RUIM_READY:
3180         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3181             return CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM;
3182
3183         case RADIO_STATE_NV_NOT_READY:
3184         case RADIO_STATE_NV_READY:
3185             return CDMA_SUBSCRIPTION_SOURCE_NV;
3186
3187         default:
3188             RLOGD("decodeCdmaSubscriptionSource: Invoked with incorrect RadioState");
3189             return -1;
3190     }
3191 }
3192
3193 static int
3194 decodeSimStatus (RIL_RadioState radioState) {
3195    switch (radioState) {
3196        case RADIO_STATE_SIM_NOT_READY:
3197        case RADIO_STATE_RUIM_NOT_READY:
3198        case RADIO_STATE_NV_NOT_READY:
3199        case RADIO_STATE_NV_READY:
3200            return -1;
3201        case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3202        case RADIO_STATE_SIM_READY:
3203        case RADIO_STATE_RUIM_READY:
3204        case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3205            return radioState;
3206        default:
3207            RLOGD("decodeSimStatus: Invoked with incorrect RadioState");
3208            return -1;
3209    }
3210 }
3211
3212 static bool is3gpp2(int radioTech) {
3213     switch (radioTech) {
3214         case RADIO_TECH_IS95A:
3215         case RADIO_TECH_IS95B:
3216         case RADIO_TECH_1xRTT:
3217         case RADIO_TECH_EVDO_0:
3218         case RADIO_TECH_EVDO_A:
3219         case RADIO_TECH_EVDO_B:
3220         case RADIO_TECH_EHRPD:
3221             return true;
3222         default:
3223             return false;
3224     }
3225 }
3226
3227 /* If RIL sends SIM states or RUIM states, store the voice radio
3228  * technology and subscription source information so that they can be
3229  * returned when telephony framework requests them
3230  */
3231 static RIL_RadioState
3232 processRadioState(RIL_RadioState newRadioState) {
3233
3234     if((newRadioState > RADIO_STATE_UNAVAILABLE) && (newRadioState < RADIO_STATE_ON)) {
3235         int newVoiceRadioTech;
3236         int newCdmaSubscriptionSource;
3237         int newSimStatus;
3238
3239         /* This is old RIL. Decode Subscription source and Voice Radio Technology
3240            from Radio State and send change notifications if there has been a change */
3241         newVoiceRadioTech = decodeVoiceRadioTechnology(newRadioState);
3242         if(newVoiceRadioTech != voiceRadioTech) {
3243             voiceRadioTech = newVoiceRadioTech;
3244             RIL_onUnsolicitedResponse (RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
3245                         &voiceRadioTech, sizeof(voiceRadioTech));
3246         }
3247         if(is3gpp2(newVoiceRadioTech)) {
3248             newCdmaSubscriptionSource = decodeCdmaSubscriptionSource(newRadioState);
3249             if(newCdmaSubscriptionSource != cdmaSubscriptionSource) {
3250                 cdmaSubscriptionSource = newCdmaSubscriptionSource;
3251                 RIL_onUnsolicitedResponse (RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
3252                         &cdmaSubscriptionSource, sizeof(cdmaSubscriptionSource));
3253             }
3254         }
3255         newSimStatus = decodeSimStatus(newRadioState);
3256         if(newSimStatus != simRuimStatus) {
3257             simRuimStatus = newSimStatus;
3258             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
3259         }
3260
3261         /* Send RADIO_ON to telephony */
3262         newRadioState = RADIO_STATE_ON;
3263     }
3264
3265     return newRadioState;
3266 }
3267
3268 extern "C"
3269 void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
3270                                 size_t datalen)
3271 {
3272     int unsolResponseIndex;
3273     int ret;
3274     int64_t timeReceived = 0;
3275     bool shouldScheduleTimeout = false;
3276     RIL_RadioState newState;
3277
3278     if (s_registerCalled == 0) {
3279         // Ignore RIL_onUnsolicitedResponse before RIL_register
3280         RLOGW("RIL_onUnsolicitedResponse called before RIL_register");
3281         return;
3282     }
3283
3284     unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
3285
3286     if ((unsolResponseIndex < 0)
3287         || (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
3288         RLOGE("unsupported unsolicited response code %d", unsolResponse);
3289         return;
3290     }
3291
3292     // Grab a wake lock if needed for this reponse,
3293     // as we exit we'll either release it immediately
3294     // or set a timer to release it later.
3295     switch (s_unsolResponses[unsolResponseIndex].wakeType) {
3296         case WAKE_PARTIAL:
3297             grabPartialWakeLock();
3298             shouldScheduleTimeout = true;
3299         break;
3300
3301         case DONT_WAKE:
3302         default:
3303             // No wake lock is grabed so don't set timeout
3304             shouldScheduleTimeout = false;
3305             break;
3306     }
3307
3308     // Mark the time this was received, doing this
3309     // after grabing the wakelock incase getting
3310     // the elapsedRealTime might cause us to goto
3311     // sleep.
3312     if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
3313         timeReceived = elapsedRealtime();
3314     }
3315
3316     appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
3317
3318     Parcel p;
3319
3320     p.writeInt32 (RESPONSE_UNSOLICITED);
3321     p.writeInt32 (unsolResponse);
3322
3323     ret = s_unsolResponses[unsolResponseIndex]
3324                 .responseFunction(p, data, datalen);
3325     if (ret != 0) {
3326         // Problem with the response. Don't continue;
3327         goto error_exit;
3328     }
3329
3330     // some things get more payload
3331     switch(unsolResponse) {
3332         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
3333             newState = processRadioState(s_callbacks.onStateRequest());
3334             p.writeInt32(newState);
3335             appendPrintBuf("%s {%s}", printBuf,
3336                 radioStateToString(s_callbacks.onStateRequest()));
3337         break;
3338
3339
3340         case RIL_UNSOL_NITZ_TIME_RECEIVED:
3341             // Store the time that this was received so the
3342             // handler of this message can account for
3343             // the time it takes to arrive and process. In
3344             // particular the system has been known to sleep
3345             // before this message can be processed.
3346             p.writeInt64(timeReceived);
3347         break;
3348     }
3349
3350     ret = sendResponse(p);
3351     if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
3352
3353         // Unfortunately, NITZ time is not poll/update like everything
3354         // else in the system. So, if the upstream client isn't connected,
3355         // keep a copy of the last NITZ response (with receive time noted
3356         // above) around so we can deliver it when it is connected
3357
3358         if (s_lastNITZTimeData != NULL) {
3359             free (s_lastNITZTimeData);
3360             s_lastNITZTimeData = NULL;
3361         }
3362
3363         s_lastNITZTimeData = malloc(p.dataSize());
3364         s_lastNITZTimeDataSize = p.dataSize();
3365         memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
3366     }
3367
3368     // For now, we automatically go back to sleep after TIMEVAL_WAKE_TIMEOUT
3369     // FIXME The java code should handshake here to release wake lock
3370
3371     if (shouldScheduleTimeout) {
3372         // Cancel the previous request
3373         if (s_last_wake_timeout_info != NULL) {
3374             s_last_wake_timeout_info->userParam = (void *)1;
3375         }
3376
3377         s_last_wake_timeout_info
3378             = internalRequestTimedCallback(wakeTimeoutCallback, NULL,
3379                                             &TIMEVAL_WAKE_TIMEOUT);
3380     }
3381
3382     // Normal exit
3383     return;
3384
3385 error_exit:
3386     if (shouldScheduleTimeout) {
3387         releaseWakeLock();
3388     }
3389 }
3390
3391 /** FIXME generalize this if you track UserCAllbackInfo, clear it
3392     when the callback occurs
3393 */
3394 static UserCallbackInfo *
3395 internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
3396                                 const struct timeval *relativeTime)
3397 {
3398     struct timeval myRelativeTime;
3399     UserCallbackInfo *p_info;
3400
3401     p_info = (UserCallbackInfo *) malloc (sizeof(UserCallbackInfo));
3402
3403     p_info->p_callback = callback;
3404     p_info->userParam = param;
3405
3406     if (relativeTime == NULL) {
3407         /* treat null parameter as a 0 relative time */
3408         memset (&myRelativeTime, 0, sizeof(myRelativeTime));
3409     } else {
3410         /* FIXME I think event_add's tv param is really const anyway */
3411         memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
3412     }
3413
3414     ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
3415
3416     ril_timer_add(&(p_info->event), &myRelativeTime);
3417
3418     triggerEvLoop();
3419     return p_info;
3420 }
3421
3422
3423 extern "C" void
3424 RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
3425                                 const struct timeval *relativeTime) {
3426     internalRequestTimedCallback (callback, param, relativeTime);
3427 }
3428
3429 const char *
3430 failCauseToString(RIL_Errno e) {
3431     switch(e) {
3432         case RIL_E_SUCCESS: return "E_SUCCESS";
3433         case RIL_E_RADIO_NOT_AVAILABLE: return "E_RAIDO_NOT_AVAILABLE";
3434         case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
3435         case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
3436         case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
3437         case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
3438         case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
3439         case RIL_E_CANCELLED: return "E_CANCELLED";
3440         case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
3441         case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
3442         case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
3443         case RIL_E_SIM_ABSENT:return "E_SIM_ABSENT";
3444         case RIL_E_ILLEGAL_SIM_OR_ME:return "E_ILLEGAL_SIM_OR_ME";
3445 #ifdef FEATURE_MULTIMODE_ANDROID
3446         case RIL_E_SUBSCRIPTION_NOT_AVAILABLE:return "E_SUBSCRIPTION_NOT_AVAILABLE";
3447         case RIL_E_MODE_NOT_SUPPORTED:return "E_MODE_NOT_SUPPORTED";
3448 #endif
3449         default: return "<unknown error>";
3450     }
3451 }
3452
3453 const char *
3454 radioStateToString(RIL_RadioState s) {
3455     switch(s) {
3456         case RADIO_STATE_OFF: return "RADIO_OFF";
3457         case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
3458         case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
3459         case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
3460         case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
3461         case RADIO_STATE_RUIM_NOT_READY:return"RADIO_RUIM_NOT_READY";
3462         case RADIO_STATE_RUIM_READY:return"RADIO_RUIM_READY";
3463         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:return"RADIO_RUIM_LOCKED_OR_ABSENT";
3464         case RADIO_STATE_NV_NOT_READY:return"RADIO_NV_NOT_READY";
3465         case RADIO_STATE_NV_READY:return"RADIO_NV_READY";
3466         case RADIO_STATE_ON:return"RADIO_ON";
3467         default: return "<unknown state>";
3468     }
3469 }
3470
3471 const char *
3472 callStateToString(RIL_CallState s) {
3473     switch(s) {
3474         case RIL_CALL_ACTIVE : return "ACTIVE";
3475         case RIL_CALL_HOLDING: return "HOLDING";
3476         case RIL_CALL_DIALING: return "DIALING";
3477         case RIL_CALL_ALERTING: return "ALERTING";
3478         case RIL_CALL_INCOMING: return "INCOMING";
3479         case RIL_CALL_WAITING: return "WAITING";
3480         default: return "<unknown state>";
3481     }
3482 }
3483
3484 const char *
3485 requestToString(int request) {
3486 /*
3487  cat libs/telephony/ril_commands.h \
3488  | egrep "^ *{RIL_" \
3489  | sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
3490
3491
3492  cat libs/telephony/ril_unsol_commands.h \
3493  | egrep "^ *{RIL_" \
3494  | sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
3495
3496 */
3497     switch(request) {
3498         case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
3499         case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
3500         case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
3501         case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
3502         case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
3503         case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
3504         case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
3505         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
3506         case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
3507         case RIL_REQUEST_DIAL: return "DIAL";
3508         case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
3509         case RIL_REQUEST_HANGUP: return "HANGUP";
3510         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
3511         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
3512         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
3513         case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
3514         case RIL_REQUEST_UDUB: return "UDUB";
3515         case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
3516         case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
3517         case RIL_REQUEST_VOICE_REGISTRATION_STATE: return "VOICE_REGISTRATION_STATE";
3518         case RIL_REQUEST_DATA_REGISTRATION_STATE: return "DATA_REGISTRATION_STATE";
3519         case RIL_REQUEST_OPERATOR: return "OPERATOR";
3520         case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
3521         case RIL_REQUEST_DTMF: return "DTMF";
3522         case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
3523         case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
3524         case RIL_REQUEST_SETUP_DATA_CALL: return "SETUP_DATA_CALL";
3525         case RIL_REQUEST_SIM_IO: return "SIM_IO";
3526         case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
3527         case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
3528         case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
3529         case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
3530         case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
3531         case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
3532         case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
3533         case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
3534         case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
3535         case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
3536         case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
3537         case RIL_REQUEST_ANSWER: return "ANSWER";
3538         case RIL_REQUEST_DEACTIVATE_DATA_CALL: return "DEACTIVATE_DATA_CALL";
3539         case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
3540         case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
3541         case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
3542         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
3543         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
3544         case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
3545         case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
3546         case RIL_REQUEST_DTMF_START: return "DTMF_START";
3547         case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
3548         case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
3549         case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
3550         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
3551         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
3552         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
3553         case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
3554         case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
3555         case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
3556         case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: return "LAST_DATA_CALL_FAIL_CAUSE";
3557         case RIL_REQUEST_DATA_CALL_LIST: return "DATA_CALL_LIST";
3558         case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
3559         case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
3560         case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
3561         case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
3562         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
3563         case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
3564         case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
3565         case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
3566         case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
3567         case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
3568         case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
3569         case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
3570         case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
3571         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:return"CDMA_SET_SUBSCRIPTION_SOURCE";
3572         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:return"CDMA_SET_ROAMING_PREFERENCE";
3573         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:return"CDMA_QUERY_ROAMING_PREFERENCE";
3574         case RIL_REQUEST_SET_TTY_MODE:return"SET_TTY_MODE";
3575         case RIL_REQUEST_QUERY_TTY_MODE:return"QUERY_TTY_MODE";
3576         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE";
3577         case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE";
3578         case RIL_REQUEST_CDMA_FLASH:return"CDMA_FLASH";
3579         case RIL_REQUEST_CDMA_BURST_DTMF:return"CDMA_BURST_DTMF";
3580         case RIL_REQUEST_CDMA_SEND_SMS:return"CDMA_SEND_SMS";
3581         case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:return"CDMA_SMS_ACKNOWLEDGE";
3582         case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:return"GSM_GET_BROADCAST_SMS_CONFIG";
3583         case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:return"GSM_SET_BROADCAST_SMS_CONFIG";
3584         case RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG:return "CDMA_GET_BROADCAST_SMS_CONFIG";
3585         case RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG:return "CDMA_SET_BROADCAST_SMS_CONFIG";
3586         case RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION:return "CDMA_SMS_BROADCAST_ACTIVATION";
3587         case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: return"CDMA_VALIDATE_AND_WRITE_AKEY";
3588         case RIL_REQUEST_CDMA_SUBSCRIPTION: return"CDMA_SUBSCRIPTION";
3589         case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: return "CDMA_WRITE_SMS_TO_RUIM";
3590         case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: return "CDMA_DELETE_SMS_ON_RUIM";
3591         case RIL_REQUEST_DEVICE_IDENTITY: return "DEVICE_IDENTITY";
3592         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: return "EXIT_EMERGENCY_CALLBACK_MODE";
3593         case RIL_REQUEST_GET_SMSC_ADDRESS: return "GET_SMSC_ADDRESS";
3594         case RIL_REQUEST_SET_SMSC_ADDRESS: return "SET_SMSC_ADDRESS";
3595         case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: return "REPORT_SMS_MEMORY_STATUS";
3596         case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: return "REPORT_STK_SERVICE_IS_RUNNING";
3597         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE: return "CDMA_GET_SUBSCRIPTION_SOURCE";
3598         case RIL_REQUEST_ISIM_AUTHENTICATION: return "ISIM_AUTHENTICATION";
3599         case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: return "RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU";
3600         case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: return "RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS";
3601         case RIL_REQUEST_VOICE_RADIO_TECH: return "VOICE_RADIO_TECH";
3602         case RIL_REQUEST_GET_CELL_INFO_LIST: return"GET_CELL_INFO_LIST";
3603         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE: return"SET_UNSOL_CELL_INFO_LIST_RATE";
3604         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
3605         case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
3606         case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED";
3607         case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
3608         case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
3609         case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
3610         case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
3611         case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
3612         case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
3613         case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
3614         case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
3615         case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
3616         case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
3617         case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
3618         case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
3619         case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
3620         case RIL_UNSOL_DATA_CALL_LIST_CHANGED: return "UNSOL_DATA_CALL_LIST_CHANGED";
3621         case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
3622         case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED: return "UNSOL_RESPONSE_SIM_STATUS_CHANGED";
3623         case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS: return "UNSOL_NEW_CDMA_SMS";
3624         case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS: return "UNSOL_NEW_BROADCAST_SMS";
3625         case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL: return "UNSOL_CDMA_RUIM_SMS_STORAGE_FULL";
3626         case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "UNSOL_RESTRICTED_STATE_CHANGED";
3627         case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE: return "UNSOL_ENTER_EMERGENCY_CALLBACK_MODE";
3628         case RIL_UNSOL_CDMA_CALL_WAITING: return "UNSOL_CDMA_CALL_WAITING";
3629         case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS: return "UNSOL_CDMA_OTA_PROVISION_STATUS";
3630         case RIL_UNSOL_CDMA_INFO_REC: return "UNSOL_CDMA_INFO_REC";
3631         case RIL_UNSOL_OEM_HOOK_RAW: return "UNSOL_OEM_HOOK_RAW";
3632         case RIL_UNSOL_RINGBACK_TONE: return "UNSOL_RINGBACK_TONE";
3633         case RIL_UNSOL_RESEND_INCALL_MUTE: return "UNSOL_RESEND_INCALL_MUTE";
3634         case RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED: return "UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED";
3635         case RIL_UNSOL_CDMA_PRL_CHANGED: return "UNSOL_CDMA_PRL_CHANGED";
3636         case RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE: return "UNSOL_EXIT_EMERGENCY_CALLBACK_MODE";
3637         case RIL_UNSOL_RIL_CONNECTED: return "UNSOL_RIL_CONNECTED";
3638         case RIL_UNSOL_VOICE_RADIO_TECH_CHANGED: return "UNSOL_VOICE_RADIO_TECH_CHANGED";
3639         case RIL_UNSOL_CELL_INFO_LIST: return "UNSOL_CELL_INFO_LIST";
3640         default: return "<unknown request>";
3641     }
3642 }
3643
3644 } /* namespace android */