OSDN Git Service

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