OSDN Git Service

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