OSDN Git Service

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