OSDN Git Service

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