OSDN Git Service

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