OSDN Git Service

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