OSDN Git Service

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