OSDN Git Service

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