OSDN Git Service

am 1b4c3db6: Merge "RIL: Support SMS on IMS, DO NOT MERGE" into jb-mr2-dev
[android-x86/hardware-ril.git] / libril / ril.cpp
1 /* //device/libs/telephony/ril.cpp
2 **
3 ** Copyright 2006, The Android Open Source Project
4 ** Copyright (c) 2012, The Linux Foundation. All rights reserved.
5 **
6 ** Licensed under the Apache License, Version 2.0 (the "License");
7 ** you may not use this file except in compliance with the License.
8 ** You may obtain a copy of the License at
9 **
10 **     http://www.apache.org/licenses/LICENSE-2.0
11 **
12 ** Unless required by applicable law or agreed to in writing, software
13 ** distributed under the License is distributed on an "AS IS" BASIS,
14 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 ** See the License for the specific language governing permissions and
16 ** limitations under the License.
17 */
18
19 #define LOG_TAG "RILC"
20
21 #include <hardware_legacy/power.h>
22
23 #include <telephony/ril.h>
24 #include <telephony/ril_cdma_sms.h>
25 #include <cutils/sockets.h>
26 #include <cutils/jstring.h>
27 #include <cutils/record_stream.h>
28 #include <utils/Log.h>
29 #include <utils/SystemClock.h>
30 #include <pthread.h>
31 #include <binder/Parcel.h>
32 #include <cutils/jstring.h>
33
34 #include <sys/types.h>
35 #include <sys/limits.h>
36 #include <pwd.h>
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <stdarg.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <time.h>
45 #include <errno.h>
46 #include <assert.h>
47 #include <ctype.h>
48 #include <alloca.h>
49 #include <sys/un.h>
50 #include <assert.h>
51 #include <netinet/in.h>
52 #include <cutils/properties.h>
53
54 #include <ril_event.h>
55
56 namespace android {
57
58 #define PHONE_PROCESS "radio"
59
60 #define SOCKET_NAME_RIL "rild"
61 #define SOCKET_NAME_RIL_DEBUG "rild-debug"
62
63 #define ANDROID_WAKE_LOCK_NAME "radio-interface"
64
65
66 #define PROPERTY_RIL_IMPL "gsm.version.ril-impl"
67
68 // match with constant in RIL.java
69 #define MAX_COMMAND_BYTES (8 * 1024)
70
71 // Basically: memset buffers that the client library
72 // shouldn't be using anymore in an attempt to find
73 // memory usage issues sooner.
74 #define MEMSET_FREED 1
75
76 #define NUM_ELEMS(a)     (sizeof (a) / sizeof (a)[0])
77
78 #define MIN(a,b) ((a)<(b) ? (a) : (b))
79
80 /* Constants for response types */
81 #define RESPONSE_SOLICITED 0
82 #define RESPONSE_UNSOLICITED 1
83
84 /* Negative values for private RIL errno's */
85 #define RIL_ERRNO_INVALID_RESPONSE -1
86
87 // request, response, and unsolicited msg print macro
88 #define PRINTBUF_SIZE 8096
89
90 // Enable RILC log
91 #define RILC_LOG 0
92
93 #if RILC_LOG
94     #define startRequest           sprintf(printBuf, "(")
95     #define closeRequest           sprintf(printBuf, "%s)", printBuf)
96     #define printRequest(token, req)           \
97             RLOGD("[%04d]> %s %s", token, requestToString(req), printBuf)
98
99     #define startResponse           sprintf(printBuf, "%s {", printBuf)
100     #define closeResponse           sprintf(printBuf, "%s}", printBuf)
101     #define printResponse           RLOGD("%s", printBuf)
102
103     #define clearPrintBuf           printBuf[0] = 0
104     #define removeLastChar          printBuf[strlen(printBuf)-1] = 0
105     #define appendPrintBuf(x...)    sprintf(printBuf, x)
106 #else
107     #define startRequest
108     #define closeRequest
109     #define printRequest(token, req)
110     #define startResponse
111     #define closeResponse
112     #define printResponse
113     #define clearPrintBuf
114     #define removeLastChar
115     #define appendPrintBuf(x...)
116 #endif
117
118 enum WakeType {DONT_WAKE, WAKE_PARTIAL};
119
120 typedef struct {
121     int requestNumber;
122     void (*dispatchFunction) (Parcel &p, struct RequestInfo *pRI);
123     int(*responseFunction) (Parcel &p, void *response, size_t responselen);
124 } CommandInfo;
125
126 typedef struct {
127     int requestNumber;
128     int (*responseFunction) (Parcel &p, void *response, size_t responselen);
129     WakeType wakeType;
130 } UnsolResponseInfo;
131
132 typedef struct RequestInfo {
133     int32_t token;      //this is not RIL_Token
134     CommandInfo *pCI;
135     struct RequestInfo *p_next;
136     char cancelled;
137     char local;         // responses to local commands do not go back to command process
138 } RequestInfo;
139
140 typedef struct UserCallbackInfo {
141     RIL_TimedCallback p_callback;
142     void *userParam;
143     struct ril_event event;
144     struct UserCallbackInfo *p_next;
145 } UserCallbackInfo;
146
147
148 /*******************************************************************/
149
150 RIL_RadioFunctions s_callbacks = {0, NULL, NULL, NULL, NULL, NULL};
151 static int s_registerCalled = 0;
152
153 static pthread_t s_tid_dispatch;
154 static pthread_t s_tid_reader;
155 static int s_started = 0;
156
157 static int s_fdListen = -1;
158 static int s_fdCommand = -1;
159 static int s_fdDebug = -1;
160
161 static int s_fdWakeupRead;
162 static int s_fdWakeupWrite;
163
164 static struct ril_event s_commands_event;
165 static struct ril_event s_wakeupfd_event;
166 static struct ril_event s_listen_event;
167 static struct ril_event s_wake_timeout_event;
168 static struct ril_event s_debug_event;
169
170
171 static const struct timeval TIMEVAL_WAKE_TIMEOUT = {1,0};
172
173 static pthread_mutex_t s_pendingRequestsMutex = PTHREAD_MUTEX_INITIALIZER;
174 static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER;
175 static pthread_mutex_t s_startupMutex = PTHREAD_MUTEX_INITIALIZER;
176 static pthread_cond_t s_startupCond = PTHREAD_COND_INITIALIZER;
177
178 static pthread_mutex_t s_dispatchMutex = PTHREAD_MUTEX_INITIALIZER;
179 static pthread_cond_t s_dispatchCond = PTHREAD_COND_INITIALIZER;
180
181 static RequestInfo *s_pendingRequests = NULL;
182
183 static RequestInfo *s_toDispatchHead = NULL;
184 static RequestInfo *s_toDispatchTail = NULL;
185
186 static UserCallbackInfo *s_last_wake_timeout_info = NULL;
187
188 static void *s_lastNITZTimeData = NULL;
189 static size_t s_lastNITZTimeDataSize;
190
191 #if RILC_LOG
192     static char printBuf[PRINTBUF_SIZE];
193 #endif
194
195 /*******************************************************************/
196
197 static void dispatchVoid (Parcel& p, RequestInfo *pRI);
198 static void dispatchString (Parcel& p, RequestInfo *pRI);
199 static void dispatchStrings (Parcel& p, RequestInfo *pRI);
200 static void dispatchInts (Parcel& p, RequestInfo *pRI);
201 static void dispatchDial (Parcel& p, RequestInfo *pRI);
202 static void dispatchSIM_IO (Parcel& p, RequestInfo *pRI);
203 static void dispatchCallForward(Parcel& p, RequestInfo *pRI);
204 static void dispatchRaw(Parcel& p, RequestInfo *pRI);
205 static void dispatchSmsWrite (Parcel &p, RequestInfo *pRI);
206 static void dispatchDataCall (Parcel& p, RequestInfo *pRI);
207 static void dispatchVoiceRadioTech (Parcel& p, RequestInfo *pRI);
208 static void dispatchCdmaSubscriptionSource (Parcel& p, RequestInfo *pRI);
209
210 static void dispatchCdmaSms(Parcel &p, RequestInfo *pRI);
211 static void dispatchImsSms(Parcel &p, RequestInfo *pRI);
212 static void dispatchImsCdmaSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef);
213 static void dispatchImsGsmSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef);
214 static void dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI);
215 static void dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI);
216 static void dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI);
217 static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI);
218 static int responseInts(Parcel &p, void *response, size_t responselen);
219 static int responseStrings(Parcel &p, void *response, size_t responselen);
220 static int responseString(Parcel &p, void *response, size_t responselen);
221 static int responseVoid(Parcel &p, void *response, size_t responselen);
222 static int responseCallList(Parcel &p, void *response, size_t responselen);
223 static int responseSMS(Parcel &p, void *response, size_t responselen);
224 static int responseSIM_IO(Parcel &p, void *response, size_t responselen);
225 static int responseCallForwards(Parcel &p, void *response, size_t responselen);
226 static int responseDataCallList(Parcel &p, void *response, size_t responselen);
227 static int responseSetupDataCall(Parcel &p, void *response, size_t responselen);
228 static int responseRaw(Parcel &p, void *response, size_t responselen);
229 static int responseSsn(Parcel &p, void *response, size_t responselen);
230 static int responseSimStatus(Parcel &p, void *response, size_t responselen);
231 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen);
232 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen);
233 static int responseCdmaSms(Parcel &p, void *response, size_t responselen);
234 static int responseCellList(Parcel &p, void *response, size_t responselen);
235 static int responseCdmaInformationRecords(Parcel &p,void *response, size_t responselen);
236 static int responseRilSignalStrength(Parcel &p,void *response, size_t responselen);
237 static int responseCallRing(Parcel &p, void *response, size_t responselen);
238 static int responseCdmaSignalInfoRecord(Parcel &p,void *response, size_t responselen);
239 static int responseCdmaCallWaiting(Parcel &p,void *response, size_t responselen);
240 static int responseSimRefresh(Parcel &p, void *response, size_t responselen);
241 static int responseCellInfoList(Parcel &p, void *response, size_t responselen);
242
243 static int decodeVoiceRadioTechnology (RIL_RadioState radioState);
244 static int decodeCdmaSubscriptionSource (RIL_RadioState radioState);
245 static RIL_RadioState processRadioState(RIL_RadioState newRadioState);
246
247 extern "C" const char * requestToString(int request);
248 extern "C" const char * failCauseToString(RIL_Errno);
249 extern "C" const char * callStateToString(RIL_CallState);
250 extern "C" const char * radioStateToString(RIL_RadioState);
251
252 #ifdef RIL_SHLIB
253 extern "C" void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
254                                 size_t datalen);
255 #endif
256
257 static UserCallbackInfo * internalRequestTimedCallback
258     (RIL_TimedCallback callback, void *param,
259         const struct timeval *relativeTime);
260
261 /** Index == requestNumber */
262 static CommandInfo s_commands[] = {
263 #include "ril_commands.h"
264 };
265
266 static UnsolResponseInfo s_unsolResponses[] = {
267 #include "ril_unsol_commands.h"
268 };
269
270 /* For older RILs that do not support new commands RIL_REQUEST_VOICE_RADIO_TECH and
271    RIL_UNSOL_VOICE_RADIO_TECH_CHANGED messages, decode the voice radio tech from
272    radio state message and store it. Every time there is a change in Radio State
273    check to see if voice radio tech changes and notify telephony
274  */
275 int voiceRadioTech = -1;
276
277 /* For older RILs that do not support new commands RIL_REQUEST_GET_CDMA_SUBSCRIPTION_SOURCE
278    and RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED messages, decode the subscription
279    source from radio state and store it. Every time there is a change in Radio State
280    check to see if subscription source changed and notify telephony
281  */
282 int cdmaSubscriptionSource = -1;
283
284 /* For older RILs that do not send RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, decode the
285    SIM/RUIM state from radio state and store it. Every time there is a change in Radio State,
286    check to see if SIM/RUIM status changed and notify telephony
287  */
288 int simRuimStatus = -1;
289
290 static char *
291 strdupReadString(Parcel &p) {
292     size_t stringlen;
293     const char16_t *s16;
294
295     s16 = p.readString16Inplace(&stringlen);
296
297     return strndup16to8(s16, stringlen);
298 }
299
300 static void writeStringToParcel(Parcel &p, const char *s) {
301     char16_t *s16;
302     size_t s16_len;
303     s16 = strdup8to16(s, &s16_len);
304     p.writeString16(s16, s16_len);
305     free(s16);
306 }
307
308
309 static void
310 memsetString (char *s) {
311     if (s != NULL) {
312         memset (s, 0, strlen(s));
313     }
314 }
315
316 void   nullParcelReleaseFunction (const uint8_t* data, size_t dataSize,
317                                     const size_t* objects, size_t objectsSize,
318                                         void* cookie) {
319     // do nothing -- the data reference lives longer than the Parcel object
320 }
321
322 /**
323  * To be called from dispatch thread
324  * Issue a single local request, ensuring that the response
325  * is not sent back up to the command process
326  */
327 static void
328 issueLocalRequest(int request, void *data, int len) {
329     RequestInfo *pRI;
330     int ret;
331
332     pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
333
334     pRI->local = 1;
335     pRI->token = 0xffffffff;        // token is not used in this context
336     pRI->pCI = &(s_commands[request]);
337
338     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
339     assert (ret == 0);
340
341     pRI->p_next = s_pendingRequests;
342     s_pendingRequests = pRI;
343
344     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
345     assert (ret == 0);
346
347     RLOGD("C[locl]> %s", requestToString(request));
348
349     s_callbacks.onRequest(request, data, len, pRI);
350 }
351
352
353
354 static int
355 processCommandBuffer(void *buffer, size_t buflen) {
356     Parcel p;
357     status_t status;
358     int32_t request;
359     int32_t token;
360     RequestInfo *pRI;
361     int ret;
362
363     p.setData((uint8_t *) buffer, buflen);
364
365     // status checked at end
366     status = p.readInt32(&request);
367     status = p.readInt32 (&token);
368
369     if (status != NO_ERROR) {
370         RLOGE("invalid request block");
371         return 0;
372     }
373
374     if (request < 1 || request >= (int32_t)NUM_ELEMS(s_commands)) {
375         RLOGE("unsupported request code %d token %d", request, token);
376         // FIXME this should perhaps return a response
377         return 0;
378     }
379
380
381     pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
382
383     pRI->token = token;
384     pRI->pCI = &(s_commands[request]);
385
386     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
387     assert (ret == 0);
388
389     pRI->p_next = s_pendingRequests;
390     s_pendingRequests = pRI;
391
392     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
393     assert (ret == 0);
394
395 /*    sLastDispatchedToken = token; */
396
397     pRI->pCI->dispatchFunction(p, pRI);
398
399     return 0;
400 }
401
402 static void
403 invalidCommandBlock (RequestInfo *pRI) {
404     RLOGE("invalid command block for token %d request %s",
405                 pRI->token, requestToString(pRI->pCI->requestNumber));
406 }
407
408 /** Callee expects NULL */
409 static void
410 dispatchVoid (Parcel& p, RequestInfo *pRI) {
411     clearPrintBuf;
412     printRequest(pRI->token, pRI->pCI->requestNumber);
413     s_callbacks.onRequest(pRI->pCI->requestNumber, NULL, 0, pRI);
414 }
415
416 /** Callee expects const char * */
417 static void
418 dispatchString (Parcel& p, RequestInfo *pRI) {
419     status_t status;
420     size_t datalen;
421     size_t stringlen;
422     char *string8 = NULL;
423
424     string8 = strdupReadString(p);
425
426     startRequest;
427     appendPrintBuf("%s%s", printBuf, string8);
428     closeRequest;
429     printRequest(pRI->token, pRI->pCI->requestNumber);
430
431     s_callbacks.onRequest(pRI->pCI->requestNumber, string8,
432                        sizeof(char *), pRI);
433
434 #ifdef MEMSET_FREED
435     memsetString(string8);
436 #endif
437
438     free(string8);
439     return;
440 invalid:
441     invalidCommandBlock(pRI);
442     return;
443 }
444
445 /** Callee expects const char ** */
446 static void
447 dispatchStrings (Parcel &p, RequestInfo *pRI) {
448     int32_t countStrings;
449     status_t status;
450     size_t datalen;
451     char **pStrings;
452
453     status = p.readInt32 (&countStrings);
454
455     if (status != NO_ERROR) {
456         goto invalid;
457     }
458
459     startRequest;
460     if (countStrings == 0) {
461         // just some non-null pointer
462         pStrings = (char **)alloca(sizeof(char *));
463         datalen = 0;
464     } else if (((int)countStrings) == -1) {
465         pStrings = NULL;
466         datalen = 0;
467     } else {
468         datalen = sizeof(char *) * countStrings;
469
470         pStrings = (char **)alloca(datalen);
471
472         for (int i = 0 ; i < countStrings ; i++) {
473             pStrings[i] = strdupReadString(p);
474             appendPrintBuf("%s%s,", printBuf, pStrings[i]);
475         }
476     }
477     removeLastChar;
478     closeRequest;
479     printRequest(pRI->token, pRI->pCI->requestNumber);
480
481     s_callbacks.onRequest(pRI->pCI->requestNumber, pStrings, datalen, pRI);
482
483     if (pStrings != NULL) {
484         for (int i = 0 ; i < countStrings ; i++) {
485 #ifdef MEMSET_FREED
486             memsetString (pStrings[i]);
487 #endif
488             free(pStrings[i]);
489         }
490
491 #ifdef MEMSET_FREED
492         memset(pStrings, 0, datalen);
493 #endif
494     }
495
496     return;
497 invalid:
498     invalidCommandBlock(pRI);
499     return;
500 }
501
502 /** Callee expects const int * */
503 static void
504 dispatchInts (Parcel &p, RequestInfo *pRI) {
505     int32_t count;
506     status_t status;
507     size_t datalen;
508     int *pInts;
509
510     status = p.readInt32 (&count);
511
512     if (status != NO_ERROR || count == 0) {
513         goto invalid;
514     }
515
516     datalen = sizeof(int) * count;
517     pInts = (int *)alloca(datalen);
518
519     startRequest;
520     for (int i = 0 ; i < count ; i++) {
521         int32_t t;
522
523         status = p.readInt32(&t);
524         pInts[i] = (int)t;
525         appendPrintBuf("%s%d,", printBuf, t);
526
527         if (status != NO_ERROR) {
528             goto invalid;
529         }
530    }
531    removeLastChar;
532    closeRequest;
533    printRequest(pRI->token, pRI->pCI->requestNumber);
534
535    s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<int *>(pInts),
536                        datalen, pRI);
537
538 #ifdef MEMSET_FREED
539     memset(pInts, 0, datalen);
540 #endif
541
542     return;
543 invalid:
544     invalidCommandBlock(pRI);
545     return;
546 }
547
548
549 /**
550  * Callee expects const RIL_SMS_WriteArgs *
551  * Payload is:
552  *   int32_t status
553  *   String pdu
554  */
555 static void
556 dispatchSmsWrite (Parcel &p, RequestInfo *pRI) {
557     RIL_SMS_WriteArgs args;
558     int32_t t;
559     status_t status;
560
561     memset (&args, 0, sizeof(args));
562
563     status = p.readInt32(&t);
564     args.status = (int)t;
565
566     args.pdu = strdupReadString(p);
567
568     if (status != NO_ERROR || args.pdu == NULL) {
569         goto invalid;
570     }
571
572     args.smsc = strdupReadString(p);
573
574     startRequest;
575     appendPrintBuf("%s%d,%s,smsc=%s", printBuf, args.status,
576         (char*)args.pdu,  (char*)args.smsc);
577     closeRequest;
578     printRequest(pRI->token, pRI->pCI->requestNumber);
579
580     s_callbacks.onRequest(pRI->pCI->requestNumber, &args, sizeof(args), pRI);
581
582 #ifdef MEMSET_FREED
583     memsetString (args.pdu);
584 #endif
585
586     free (args.pdu);
587
588 #ifdef MEMSET_FREED
589     memset(&args, 0, sizeof(args));
590 #endif
591
592     return;
593 invalid:
594     invalidCommandBlock(pRI);
595     return;
596 }
597
598 /**
599  * Callee expects const RIL_Dial *
600  * Payload is:
601  *   String address
602  *   int32_t clir
603  */
604 static void
605 dispatchDial (Parcel &p, RequestInfo *pRI) {
606     RIL_Dial dial;
607     RIL_UUS_Info uusInfo;
608     int32_t sizeOfDial;
609     int32_t t;
610     int32_t uusPresent;
611     status_t status;
612
613     memset (&dial, 0, sizeof(dial));
614
615     dial.address = strdupReadString(p);
616
617     status = p.readInt32(&t);
618     dial.clir = (int)t;
619
620     if (status != NO_ERROR || dial.address == NULL) {
621         goto invalid;
622     }
623
624     if (s_callbacks.version < 3) { // Remove when partners upgrade to version 3
625         uusPresent = 0;
626         sizeOfDial = sizeof(dial) - sizeof(RIL_UUS_Info *);
627     } else {
628         status = p.readInt32(&uusPresent);
629
630         if (status != NO_ERROR) {
631             goto invalid;
632         }
633
634         if (uusPresent == 0) {
635             dial.uusInfo = NULL;
636         } else {
637             int32_t len;
638
639             memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
640
641             status = p.readInt32(&t);
642             uusInfo.uusType = (RIL_UUS_Type) t;
643
644             status = p.readInt32(&t);
645             uusInfo.uusDcs = (RIL_UUS_DCS) t;
646
647             status = p.readInt32(&len);
648             if (status != NO_ERROR) {
649                 goto invalid;
650             }
651
652             // The java code writes -1 for null arrays
653             if (((int) len) == -1) {
654                 uusInfo.uusData = NULL;
655                 len = 0;
656             } else {
657                 uusInfo.uusData = (char*) p.readInplace(len);
658             }
659
660             uusInfo.uusLength = len;
661             dial.uusInfo = &uusInfo;
662         }
663         sizeOfDial = sizeof(dial);
664     }
665
666     startRequest;
667     appendPrintBuf("%snum=%s,clir=%d", printBuf, dial.address, dial.clir);
668     if (uusPresent) {
669         appendPrintBuf("%s,uusType=%d,uusDcs=%d,uusLen=%d", printBuf,
670                 dial.uusInfo->uusType, dial.uusInfo->uusDcs,
671                 dial.uusInfo->uusLength);
672     }
673     closeRequest;
674     printRequest(pRI->token, pRI->pCI->requestNumber);
675
676     s_callbacks.onRequest(pRI->pCI->requestNumber, &dial, sizeOfDial, pRI);
677
678 #ifdef MEMSET_FREED
679     memsetString (dial.address);
680 #endif
681
682     free (dial.address);
683
684 #ifdef MEMSET_FREED
685     memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
686     memset(&dial, 0, sizeof(dial));
687 #endif
688
689     return;
690 invalid:
691     invalidCommandBlock(pRI);
692     return;
693 }
694
695 /**
696  * Callee expects const RIL_SIM_IO *
697  * Payload is:
698  *   int32_t command
699  *   int32_t fileid
700  *   String path
701  *   int32_t p1, p2, p3
702  *   String data
703  *   String pin2
704  *   String aidPtr
705  */
706 static void
707 dispatchSIM_IO (Parcel &p, RequestInfo *pRI) {
708     union RIL_SIM_IO {
709         RIL_SIM_IO_v6 v6;
710         RIL_SIM_IO_v5 v5;
711     } simIO;
712
713     int32_t t;
714     int size;
715     status_t status;
716
717     memset (&simIO, 0, sizeof(simIO));
718
719     // note we only check status at the end
720
721     status = p.readInt32(&t);
722     simIO.v6.command = (int)t;
723
724     status = p.readInt32(&t);
725     simIO.v6.fileid = (int)t;
726
727     simIO.v6.path = strdupReadString(p);
728
729     status = p.readInt32(&t);
730     simIO.v6.p1 = (int)t;
731
732     status = p.readInt32(&t);
733     simIO.v6.p2 = (int)t;
734
735     status = p.readInt32(&t);
736     simIO.v6.p3 = (int)t;
737
738     simIO.v6.data = strdupReadString(p);
739     simIO.v6.pin2 = strdupReadString(p);
740     simIO.v6.aidPtr = strdupReadString(p);
741
742     startRequest;
743     appendPrintBuf("%scmd=0x%X,efid=0x%X,path=%s,%d,%d,%d,%s,pin2=%s,aid=%s", printBuf,
744         simIO.v6.command, simIO.v6.fileid, (char*)simIO.v6.path,
745         simIO.v6.p1, simIO.v6.p2, simIO.v6.p3,
746         (char*)simIO.v6.data,  (char*)simIO.v6.pin2, simIO.v6.aidPtr);
747     closeRequest;
748     printRequest(pRI->token, pRI->pCI->requestNumber);
749
750     if (status != NO_ERROR) {
751         goto invalid;
752     }
753
754     size = (s_callbacks.version < 6) ? sizeof(simIO.v5) : sizeof(simIO.v6);
755     s_callbacks.onRequest(pRI->pCI->requestNumber, &simIO, size, pRI);
756
757 #ifdef MEMSET_FREED
758     memsetString (simIO.v6.path);
759     memsetString (simIO.v6.data);
760     memsetString (simIO.v6.pin2);
761     memsetString (simIO.v6.aidPtr);
762 #endif
763
764     free (simIO.v6.path);
765     free (simIO.v6.data);
766     free (simIO.v6.pin2);
767     free (simIO.v6.aidPtr);
768
769 #ifdef MEMSET_FREED
770     memset(&simIO, 0, sizeof(simIO));
771 #endif
772
773     return;
774 invalid:
775     invalidCommandBlock(pRI);
776     return;
777 }
778
779 /**
780  * Callee expects const RIL_CallForwardInfo *
781  * Payload is:
782  *  int32_t status/action
783  *  int32_t reason
784  *  int32_t serviceCode
785  *  int32_t toa
786  *  String number  (0 length -> null)
787  *  int32_t timeSeconds
788  */
789 static void
790 dispatchCallForward(Parcel &p, RequestInfo *pRI) {
791     RIL_CallForwardInfo cff;
792     int32_t t;
793     status_t status;
794
795     memset (&cff, 0, sizeof(cff));
796
797     // note we only check status at the end
798
799     status = p.readInt32(&t);
800     cff.status = (int)t;
801
802     status = p.readInt32(&t);
803     cff.reason = (int)t;
804
805     status = p.readInt32(&t);
806     cff.serviceClass = (int)t;
807
808     status = p.readInt32(&t);
809     cff.toa = (int)t;
810
811     cff.number = strdupReadString(p);
812
813     status = p.readInt32(&t);
814     cff.timeSeconds = (int)t;
815
816     if (status != NO_ERROR) {
817         goto invalid;
818     }
819
820     // special case: number 0-length fields is null
821
822     if (cff.number != NULL && strlen (cff.number) == 0) {
823         cff.number = NULL;
824     }
825
826     startRequest;
827     appendPrintBuf("%sstat=%d,reason=%d,serv=%d,toa=%d,%s,tout=%d", printBuf,
828         cff.status, cff.reason, cff.serviceClass, cff.toa,
829         (char*)cff.number, cff.timeSeconds);
830     closeRequest;
831     printRequest(pRI->token, pRI->pCI->requestNumber);
832
833     s_callbacks.onRequest(pRI->pCI->requestNumber, &cff, sizeof(cff), pRI);
834
835 #ifdef MEMSET_FREED
836     memsetString(cff.number);
837 #endif
838
839     free (cff.number);
840
841 #ifdef MEMSET_FREED
842     memset(&cff, 0, sizeof(cff));
843 #endif
844
845     return;
846 invalid:
847     invalidCommandBlock(pRI);
848     return;
849 }
850
851
852 static void
853 dispatchRaw(Parcel &p, RequestInfo *pRI) {
854     int32_t len;
855     status_t status;
856     const void *data;
857
858     status = p.readInt32(&len);
859
860     if (status != NO_ERROR) {
861         goto invalid;
862     }
863
864     // The java code writes -1 for null arrays
865     if (((int)len) == -1) {
866         data = NULL;
867         len = 0;
868     }
869
870     data = p.readInplace(len);
871
872     startRequest;
873     appendPrintBuf("%sraw_size=%d", printBuf, len);
874     closeRequest;
875     printRequest(pRI->token, pRI->pCI->requestNumber);
876
877     s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<void *>(data), len, pRI);
878
879     return;
880 invalid:
881     invalidCommandBlock(pRI);
882     return;
883 }
884
885 static status_t
886 constructCdmaSms(Parcel &p, RequestInfo *pRI, RIL_CDMA_SMS_Message& rcsm) {
887     int32_t  t;
888     uint8_t ut;
889     status_t status;
890     int32_t digitCount;
891     int digitLimit;
892
893     memset(&rcsm, 0, sizeof(rcsm));
894
895     status = p.readInt32(&t);
896     rcsm.uTeleserviceID = (int) t;
897
898     status = p.read(&ut,sizeof(ut));
899     rcsm.bIsServicePresent = (uint8_t) ut;
900
901     status = p.readInt32(&t);
902     rcsm.uServicecategory = (int) t;
903
904     status = p.readInt32(&t);
905     rcsm.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
906
907     status = p.readInt32(&t);
908     rcsm.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
909
910     status = p.readInt32(&t);
911     rcsm.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
912
913     status = p.readInt32(&t);
914     rcsm.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
915
916     status = p.read(&ut,sizeof(ut));
917     rcsm.sAddress.number_of_digits= (uint8_t) ut;
918
919     digitLimit= MIN((rcsm.sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
920     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
921         status = p.read(&ut,sizeof(ut));
922         rcsm.sAddress.digits[digitCount] = (uint8_t) ut;
923     }
924
925     status = p.readInt32(&t);
926     rcsm.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
927
928     status = p.read(&ut,sizeof(ut));
929     rcsm.sSubAddress.odd = (uint8_t) ut;
930
931     status = p.read(&ut,sizeof(ut));
932     rcsm.sSubAddress.number_of_digits = (uint8_t) ut;
933
934     digitLimit= MIN((rcsm.sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
935     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
936         status = p.read(&ut,sizeof(ut));
937         rcsm.sSubAddress.digits[digitCount] = (uint8_t) ut;
938     }
939
940     status = p.readInt32(&t);
941     rcsm.uBearerDataLen = (int) t;
942
943     digitLimit= MIN((rcsm.uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
944     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
945         status = p.read(&ut, sizeof(ut));
946         rcsm.aBearerData[digitCount] = (uint8_t) ut;
947     }
948
949     if (status != NO_ERROR) {
950         return status;
951     }
952
953     startRequest;
954     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
955             sAddress.digit_mode=%d, sAddress.Number_mode=%d, sAddress.number_type=%d, ",
956             printBuf, rcsm.uTeleserviceID,rcsm.bIsServicePresent,rcsm.uServicecategory,
957             rcsm.sAddress.digit_mode, rcsm.sAddress.number_mode,rcsm.sAddress.number_type);
958     closeRequest;
959
960     printRequest(pRI->token, pRI->pCI->requestNumber);
961
962     return status;
963 }
964
965 static void
966 dispatchCdmaSms(Parcel &p, RequestInfo *pRI) {
967     RIL_CDMA_SMS_Message rcsm;
968
969     ALOGD("dispatchCdmaSms");
970     if (NO_ERROR != constructCdmaSms(p, pRI, rcsm)) {
971         goto invalid;
972     }
973
974     s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsm, sizeof(rcsm),pRI);
975
976 #ifdef MEMSET_FREED
977     memset(&rcsm, 0, sizeof(rcsm));
978 #endif
979
980     return;
981
982 invalid:
983     invalidCommandBlock(pRI);
984     return;
985 }
986
987 static void
988 dispatchImsCdmaSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef) {
989     RIL_IMS_SMS_Message rism;
990     RIL_CDMA_SMS_Message rcsm;
991
992     ALOGD("dispatchImsCdmaSms: retry=%d, messageRef=%d", retry, messageRef);
993
994     if (NO_ERROR != constructCdmaSms(p, pRI, rcsm)) {
995         goto invalid;
996     }
997     memset(&rism, 0, sizeof(rism));
998     rism.tech = RADIO_TECH_3GPP2;
999     rism.retry = retry;
1000     rism.messageRef = messageRef;
1001     rism.message.cdmaMessage = &rcsm;
1002
1003     s_callbacks.onRequest(pRI->pCI->requestNumber, &rism,
1004             sizeof(RIL_RadioTechnologyFamily)+sizeof(uint8_t)+sizeof(int32_t)
1005             +sizeof(rcsm),pRI);
1006
1007 #ifdef MEMSET_FREED
1008     memset(&rcsm, 0, sizeof(rcsm));
1009     memset(&rism, 0, sizeof(rism));
1010 #endif
1011
1012     return;
1013
1014 invalid:
1015     invalidCommandBlock(pRI);
1016     return;
1017 }
1018
1019 static void
1020 dispatchImsGsmSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef) {
1021     RIL_IMS_SMS_Message rism;
1022     int32_t countStrings;
1023     status_t status;
1024     size_t datalen;
1025     char **pStrings;
1026     ALOGD("dispatchImsGsmSms: retry=%d, messageRef=%d", retry, messageRef);
1027
1028     status = p.readInt32 (&countStrings);
1029
1030     if (status != NO_ERROR) {
1031         goto invalid;
1032     }
1033
1034     memset(&rism, 0, sizeof(rism));
1035     rism.tech = RADIO_TECH_3GPP;
1036     rism.retry = retry;
1037     rism.messageRef = messageRef;
1038
1039     startRequest;
1040     appendPrintBuf("%sformat=%d,", printBuf, rism.tech);
1041     if (countStrings == 0) {
1042         // just some non-null pointer
1043         pStrings = (char **)alloca(sizeof(char *));
1044         datalen = 0;
1045     } else if (((int)countStrings) == -1) {
1046         pStrings = NULL;
1047         datalen = 0;
1048     } else {
1049         datalen = sizeof(char *) * countStrings;
1050
1051         pStrings = (char **)alloca(datalen);
1052
1053         for (int i = 0 ; i < countStrings ; i++) {
1054             pStrings[i] = strdupReadString(p);
1055             appendPrintBuf("%s%s,", printBuf, pStrings[i]);
1056         }
1057     }
1058     removeLastChar;
1059     closeRequest;
1060     printRequest(pRI->token, pRI->pCI->requestNumber);
1061
1062     rism.message.gsmMessage = pStrings;
1063     s_callbacks.onRequest(pRI->pCI->requestNumber, &rism,
1064             sizeof(RIL_RadioTechnologyFamily)+sizeof(uint8_t)+sizeof(int32_t)
1065             +datalen, pRI);
1066
1067     if (pStrings != NULL) {
1068         for (int i = 0 ; i < countStrings ; i++) {
1069 #ifdef MEMSET_FREED
1070             memsetString (pStrings[i]);
1071 #endif
1072             free(pStrings[i]);
1073         }
1074
1075 #ifdef MEMSET_FREED
1076         memset(pStrings, 0, datalen);
1077 #endif
1078     }
1079
1080 #ifdef MEMSET_FREED
1081     memset(&rism, 0, sizeof(rism));
1082 #endif
1083     return;
1084 invalid:
1085     ALOGE("dispatchImsGsmSms invalid block");
1086     invalidCommandBlock(pRI);
1087     return;
1088 }
1089
1090 static void
1091 dispatchImsSms(Parcel &p, RequestInfo *pRI) {
1092     int32_t  t;
1093     status_t status = p.readInt32(&t);
1094     RIL_RadioTechnologyFamily format;
1095     uint8_t retry;
1096     int32_t messageRef;
1097
1098     ALOGD("dispatchImsSms");
1099     if (status != NO_ERROR) {
1100         goto invalid;
1101     }
1102     format = (RIL_RadioTechnologyFamily) t;
1103
1104     // read retry field
1105     status = p.read(&retry,sizeof(retry));
1106     if (status != NO_ERROR) {
1107         goto invalid;
1108     }
1109     // read messageRef field
1110     status = p.read(&messageRef,sizeof(messageRef));
1111     if (status != NO_ERROR) {
1112         goto invalid;
1113     }
1114
1115     if (RADIO_TECH_3GPP == format) {
1116         dispatchImsGsmSms(p, pRI, retry, messageRef);
1117     } else if (RADIO_TECH_3GPP2 == format) {
1118         dispatchImsCdmaSms(p, pRI, retry, messageRef);
1119     } else {
1120         ALOGE("requestImsSendSMS invalid format value =%d", format);
1121     }
1122
1123     return;
1124
1125 invalid:
1126     invalidCommandBlock(pRI);
1127     return;
1128 }
1129
1130 static void
1131 dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI) {
1132     RIL_CDMA_SMS_Ack rcsa;
1133     int32_t  t;
1134     status_t status;
1135     int32_t digitCount;
1136
1137     memset(&rcsa, 0, sizeof(rcsa));
1138
1139     status = p.readInt32(&t);
1140     rcsa.uErrorClass = (RIL_CDMA_SMS_ErrorClass) t;
1141
1142     status = p.readInt32(&t);
1143     rcsa.uSMSCauseCode = (int) t;
1144
1145     if (status != NO_ERROR) {
1146         goto invalid;
1147     }
1148
1149     startRequest;
1150     appendPrintBuf("%suErrorClass=%d, uTLStatus=%d, ",
1151             printBuf, rcsa.uErrorClass, rcsa.uSMSCauseCode);
1152     closeRequest;
1153
1154     printRequest(pRI->token, pRI->pCI->requestNumber);
1155
1156     s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsa, sizeof(rcsa),pRI);
1157
1158 #ifdef MEMSET_FREED
1159     memset(&rcsa, 0, sizeof(rcsa));
1160 #endif
1161
1162     return;
1163
1164 invalid:
1165     invalidCommandBlock(pRI);
1166     return;
1167 }
1168
1169 static void
1170 dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI) {
1171     int32_t t;
1172     status_t status;
1173     int32_t num;
1174
1175     status = p.readInt32(&num);
1176     if (status != NO_ERROR) {
1177         goto invalid;
1178     }
1179
1180     {
1181         RIL_GSM_BroadcastSmsConfigInfo gsmBci[num];
1182         RIL_GSM_BroadcastSmsConfigInfo *gsmBciPtrs[num];
1183
1184         startRequest;
1185         for (int i = 0 ; i < num ; i++ ) {
1186             gsmBciPtrs[i] = &gsmBci[i];
1187
1188             status = p.readInt32(&t);
1189             gsmBci[i].fromServiceId = (int) t;
1190
1191             status = p.readInt32(&t);
1192             gsmBci[i].toServiceId = (int) t;
1193
1194             status = p.readInt32(&t);
1195             gsmBci[i].fromCodeScheme = (int) t;
1196
1197             status = p.readInt32(&t);
1198             gsmBci[i].toCodeScheme = (int) t;
1199
1200             status = p.readInt32(&t);
1201             gsmBci[i].selected = (uint8_t) t;
1202
1203             appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId =%d, \
1204                   fromCodeScheme=%d, toCodeScheme=%d, selected =%d]", printBuf, i,
1205                   gsmBci[i].fromServiceId, gsmBci[i].toServiceId,
1206                   gsmBci[i].fromCodeScheme, gsmBci[i].toCodeScheme,
1207                   gsmBci[i].selected);
1208         }
1209         closeRequest;
1210
1211         if (status != NO_ERROR) {
1212             goto invalid;
1213         }
1214
1215         s_callbacks.onRequest(pRI->pCI->requestNumber,
1216                               gsmBciPtrs,
1217                               num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *),
1218                               pRI);
1219
1220 #ifdef MEMSET_FREED
1221         memset(gsmBci, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo));
1222         memset(gsmBciPtrs, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
1223 #endif
1224     }
1225
1226     return;
1227
1228 invalid:
1229     invalidCommandBlock(pRI);
1230     return;
1231 }
1232
1233 static void
1234 dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI) {
1235     int32_t t;
1236     status_t status;
1237     int32_t num;
1238
1239     status = p.readInt32(&num);
1240     if (status != NO_ERROR) {
1241         goto invalid;
1242     }
1243
1244     {
1245         RIL_CDMA_BroadcastSmsConfigInfo cdmaBci[num];
1246         RIL_CDMA_BroadcastSmsConfigInfo *cdmaBciPtrs[num];
1247
1248         startRequest;
1249         for (int i = 0 ; i < num ; i++ ) {
1250             cdmaBciPtrs[i] = &cdmaBci[i];
1251
1252             status = p.readInt32(&t);
1253             cdmaBci[i].service_category = (int) t;
1254
1255             status = p.readInt32(&t);
1256             cdmaBci[i].language = (int) t;
1257
1258             status = p.readInt32(&t);
1259             cdmaBci[i].selected = (uint8_t) t;
1260
1261             appendPrintBuf("%s [%d: service_category=%d, language =%d, \
1262                   entries.bSelected =%d]", printBuf, i, cdmaBci[i].service_category,
1263                   cdmaBci[i].language, cdmaBci[i].selected);
1264         }
1265         closeRequest;
1266
1267         if (status != NO_ERROR) {
1268             goto invalid;
1269         }
1270
1271         s_callbacks.onRequest(pRI->pCI->requestNumber,
1272                               cdmaBciPtrs,
1273                               num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *),
1274                               pRI);
1275
1276 #ifdef MEMSET_FREED
1277         memset(cdmaBci, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo));
1278         memset(cdmaBciPtrs, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *));
1279 #endif
1280     }
1281
1282     return;
1283
1284 invalid:
1285     invalidCommandBlock(pRI);
1286     return;
1287 }
1288
1289 static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI) {
1290     RIL_CDMA_SMS_WriteArgs rcsw;
1291     int32_t  t;
1292     uint32_t ut;
1293     uint8_t  uct;
1294     status_t status;
1295     int32_t  digitCount;
1296
1297     memset(&rcsw, 0, sizeof(rcsw));
1298
1299     status = p.readInt32(&t);
1300     rcsw.status = t;
1301
1302     status = p.readInt32(&t);
1303     rcsw.message.uTeleserviceID = (int) t;
1304
1305     status = p.read(&uct,sizeof(uct));
1306     rcsw.message.bIsServicePresent = (uint8_t) uct;
1307
1308     status = p.readInt32(&t);
1309     rcsw.message.uServicecategory = (int) t;
1310
1311     status = p.readInt32(&t);
1312     rcsw.message.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
1313
1314     status = p.readInt32(&t);
1315     rcsw.message.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
1316
1317     status = p.readInt32(&t);
1318     rcsw.message.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
1319
1320     status = p.readInt32(&t);
1321     rcsw.message.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
1322
1323     status = p.read(&uct,sizeof(uct));
1324     rcsw.message.sAddress.number_of_digits = (uint8_t) uct;
1325
1326     for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_ADDRESS_MAX; digitCount ++) {
1327         status = p.read(&uct,sizeof(uct));
1328         rcsw.message.sAddress.digits[digitCount] = (uint8_t) uct;
1329     }
1330
1331     status = p.readInt32(&t);
1332     rcsw.message.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
1333
1334     status = p.read(&uct,sizeof(uct));
1335     rcsw.message.sSubAddress.odd = (uint8_t) uct;
1336
1337     status = p.read(&uct,sizeof(uct));
1338     rcsw.message.sSubAddress.number_of_digits = (uint8_t) uct;
1339
1340     for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_SUBADDRESS_MAX; digitCount ++) {
1341         status = p.read(&uct,sizeof(uct));
1342         rcsw.message.sSubAddress.digits[digitCount] = (uint8_t) uct;
1343     }
1344
1345     status = p.readInt32(&t);
1346     rcsw.message.uBearerDataLen = (int) t;
1347
1348     for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_BEARER_DATA_MAX; digitCount ++) {
1349         status = p.read(&uct, sizeof(uct));
1350         rcsw.message.aBearerData[digitCount] = (uint8_t) uct;
1351     }
1352
1353     if (status != NO_ERROR) {
1354         goto invalid;
1355     }
1356
1357     startRequest;
1358     appendPrintBuf("%sstatus=%d, message.uTeleserviceID=%d, message.bIsServicePresent=%d, \
1359             message.uServicecategory=%d, message.sAddress.digit_mode=%d, \
1360             message.sAddress.number_mode=%d, \
1361             message.sAddress.number_type=%d, ",
1362             printBuf, rcsw.status, rcsw.message.uTeleserviceID, rcsw.message.bIsServicePresent,
1363             rcsw.message.uServicecategory, rcsw.message.sAddress.digit_mode,
1364             rcsw.message.sAddress.number_mode,
1365             rcsw.message.sAddress.number_type);
1366     closeRequest;
1367
1368     printRequest(pRI->token, pRI->pCI->requestNumber);
1369
1370     s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsw, sizeof(rcsw),pRI);
1371
1372 #ifdef MEMSET_FREED
1373     memset(&rcsw, 0, sizeof(rcsw));
1374 #endif
1375
1376     return;
1377
1378 invalid:
1379     invalidCommandBlock(pRI);
1380     return;
1381
1382 }
1383
1384 // For backwards compatibility in RIL_REQUEST_SETUP_DATA_CALL.
1385 // Version 4 of the RIL interface adds a new PDP type parameter to support
1386 // IPv6 and dual-stack PDP contexts. When dealing with a previous version of
1387 // RIL, remove the parameter from the request.
1388 static void dispatchDataCall(Parcel& p, RequestInfo *pRI) {
1389     // In RIL v3, REQUEST_SETUP_DATA_CALL takes 6 parameters.
1390     const int numParamsRilV3 = 6;
1391
1392     // The first bytes of the RIL parcel contain the request number and the
1393     // serial number - see processCommandBuffer(). Copy them over too.
1394     int pos = p.dataPosition();
1395
1396     int numParams = p.readInt32();
1397     if (s_callbacks.version < 4 && numParams > numParamsRilV3) {
1398       Parcel p2;
1399       p2.appendFrom(&p, 0, pos);
1400       p2.writeInt32(numParamsRilV3);
1401       for(int i = 0; i < numParamsRilV3; i++) {
1402         p2.writeString16(p.readString16());
1403       }
1404       p2.setDataPosition(pos);
1405       dispatchStrings(p2, pRI);
1406     } else {
1407       p.setDataPosition(pos);
1408       dispatchStrings(p, pRI);
1409     }
1410 }
1411
1412 // For backwards compatibility with RILs that dont support RIL_REQUEST_VOICE_RADIO_TECH.
1413 // When all RILs handle this request, this function can be removed and
1414 // the request can be sent directly to the RIL using dispatchVoid.
1415 static void dispatchVoiceRadioTech(Parcel& p, RequestInfo *pRI) {
1416     RIL_RadioState state = s_callbacks.onStateRequest();
1417
1418     if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
1419         RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
1420     }
1421
1422     // RILs that support RADIO_STATE_ON should support this request.
1423     if (RADIO_STATE_ON == state) {
1424         dispatchVoid(p, pRI);
1425         return;
1426     }
1427
1428     // For Older RILs, that do not support RADIO_STATE_ON, assume that they
1429     // will not support this new request either and decode Voice Radio Technology
1430     // from Radio State
1431     voiceRadioTech = decodeVoiceRadioTechnology(state);
1432
1433     if (voiceRadioTech < 0)
1434         RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
1435     else
1436         RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &voiceRadioTech, sizeof(int));
1437 }
1438
1439 // For backwards compatibility in RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:.
1440 // When all RILs handle this request, this function can be removed and
1441 // the request can be sent directly to the RIL using dispatchVoid.
1442 static void dispatchCdmaSubscriptionSource(Parcel& p, RequestInfo *pRI) {
1443     RIL_RadioState state = s_callbacks.onStateRequest();
1444
1445     if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
1446         RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
1447     }
1448
1449     // RILs that support RADIO_STATE_ON should support this request.
1450     if (RADIO_STATE_ON == state) {
1451         dispatchVoid(p, pRI);
1452         return;
1453     }
1454
1455     // For Older RILs, that do not support RADIO_STATE_ON, assume that they
1456     // will not support this new request either and decode CDMA Subscription Source
1457     // from Radio State
1458     cdmaSubscriptionSource = decodeCdmaSubscriptionSource(state);
1459
1460     if (cdmaSubscriptionSource < 0)
1461         RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
1462     else
1463         RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &cdmaSubscriptionSource, sizeof(int));
1464 }
1465
1466 static int
1467 blockingWrite(int fd, const void *buffer, size_t len) {
1468     size_t writeOffset = 0;
1469     const uint8_t *toWrite;
1470
1471     toWrite = (const uint8_t *)buffer;
1472
1473     while (writeOffset < len) {
1474         ssize_t written;
1475         do {
1476             written = write (fd, toWrite + writeOffset,
1477                                 len - writeOffset);
1478         } while (written < 0 && ((errno == EINTR) || (errno == EAGAIN)));
1479
1480         if (written >= 0) {
1481             writeOffset += written;
1482         } else {   // written < 0
1483             RLOGE ("RIL Response: unexpected error on write errno:%d", errno);
1484             close(fd);
1485             return -1;
1486         }
1487     }
1488
1489     return 0;
1490 }
1491
1492 static int
1493 sendResponseRaw (const void *data, size_t dataSize) {
1494     int fd = s_fdCommand;
1495     int ret;
1496     uint32_t header;
1497
1498     if (s_fdCommand < 0) {
1499         return -1;
1500     }
1501
1502     if (dataSize > MAX_COMMAND_BYTES) {
1503         RLOGE("RIL: packet larger than %u (%u)",
1504                 MAX_COMMAND_BYTES, (unsigned int )dataSize);
1505
1506         return -1;
1507     }
1508
1509     pthread_mutex_lock(&s_writeMutex);
1510
1511     header = htonl(dataSize);
1512
1513     ret = blockingWrite(fd, (void *)&header, sizeof(header));
1514
1515     if (ret < 0) {
1516         pthread_mutex_unlock(&s_writeMutex);
1517         return ret;
1518     }
1519
1520     ret = blockingWrite(fd, data, dataSize);
1521
1522     if (ret < 0) {
1523         pthread_mutex_unlock(&s_writeMutex);
1524         return ret;
1525     }
1526
1527     pthread_mutex_unlock(&s_writeMutex);
1528
1529     return 0;
1530 }
1531
1532 static int
1533 sendResponse (Parcel &p) {
1534     printResponse;
1535     return sendResponseRaw(p.data(), p.dataSize());
1536 }
1537
1538 /** response is an int* pointing to an array of ints*/
1539
1540 static int
1541 responseInts(Parcel &p, void *response, size_t responselen) {
1542     int numInts;
1543
1544     if (response == NULL && responselen != 0) {
1545         RLOGE("invalid response: NULL");
1546         return RIL_ERRNO_INVALID_RESPONSE;
1547     }
1548     if (responselen % sizeof(int) != 0) {
1549         RLOGE("invalid response length %d expected multiple of %d\n",
1550             (int)responselen, (int)sizeof(int));
1551         return RIL_ERRNO_INVALID_RESPONSE;
1552     }
1553
1554     int *p_int = (int *) response;
1555
1556     numInts = responselen / sizeof(int *);
1557     p.writeInt32 (numInts);
1558
1559     /* each int*/
1560     startResponse;
1561     for (int i = 0 ; i < numInts ; i++) {
1562         appendPrintBuf("%s%d,", printBuf, p_int[i]);
1563         p.writeInt32(p_int[i]);
1564     }
1565     removeLastChar;
1566     closeResponse;
1567
1568     return 0;
1569 }
1570
1571 /** response is a char **, pointing to an array of char *'s
1572     The parcel will begin with the version */
1573 static int responseStringsWithVersion(int version, Parcel &p, void *response, size_t responselen) {
1574     p.writeInt32(version);
1575     return responseStrings(p, response, responselen);
1576 }
1577
1578 /** response is a char **, pointing to an array of char *'s */
1579 static int responseStrings(Parcel &p, void *response, size_t responselen) {
1580     int numStrings;
1581
1582     if (response == NULL && responselen != 0) {
1583         RLOGE("invalid response: NULL");
1584         return RIL_ERRNO_INVALID_RESPONSE;
1585     }
1586     if (responselen % sizeof(char *) != 0) {
1587         RLOGE("invalid response length %d expected multiple of %d\n",
1588             (int)responselen, (int)sizeof(char *));
1589         return RIL_ERRNO_INVALID_RESPONSE;
1590     }
1591
1592     if (response == NULL) {
1593         p.writeInt32 (0);
1594     } else {
1595         char **p_cur = (char **) response;
1596
1597         numStrings = responselen / sizeof(char *);
1598         p.writeInt32 (numStrings);
1599
1600         /* each string*/
1601         startResponse;
1602         for (int i = 0 ; i < numStrings ; i++) {
1603             appendPrintBuf("%s%s,", printBuf, (char*)p_cur[i]);
1604             writeStringToParcel (p, p_cur[i]);
1605         }
1606         removeLastChar;
1607         closeResponse;
1608     }
1609     return 0;
1610 }
1611
1612
1613 /**
1614  * NULL strings are accepted
1615  * FIXME currently ignores responselen
1616  */
1617 static int responseString(Parcel &p, void *response, size_t responselen) {
1618     /* one string only */
1619     startResponse;
1620     appendPrintBuf("%s%s", printBuf, (char*)response);
1621     closeResponse;
1622
1623     writeStringToParcel(p, (const char *)response);
1624
1625     return 0;
1626 }
1627
1628 static int responseVoid(Parcel &p, void *response, size_t responselen) {
1629     startResponse;
1630     removeLastChar;
1631     return 0;
1632 }
1633
1634 static int responseCallList(Parcel &p, void *response, size_t responselen) {
1635     int num;
1636
1637     if (response == NULL && responselen != 0) {
1638         RLOGE("invalid response: NULL");
1639         return RIL_ERRNO_INVALID_RESPONSE;
1640     }
1641
1642     if (responselen % sizeof (RIL_Call *) != 0) {
1643         RLOGE("invalid response length %d expected multiple of %d\n",
1644             (int)responselen, (int)sizeof (RIL_Call *));
1645         return RIL_ERRNO_INVALID_RESPONSE;
1646     }
1647
1648     startResponse;
1649     /* number of call info's */
1650     num = responselen / sizeof(RIL_Call *);
1651     p.writeInt32(num);
1652
1653     for (int i = 0 ; i < num ; i++) {
1654         RIL_Call *p_cur = ((RIL_Call **) response)[i];
1655         /* each call info */
1656         p.writeInt32(p_cur->state);
1657         p.writeInt32(p_cur->index);
1658         p.writeInt32(p_cur->toa);
1659         p.writeInt32(p_cur->isMpty);
1660         p.writeInt32(p_cur->isMT);
1661         p.writeInt32(p_cur->als);
1662         p.writeInt32(p_cur->isVoice);
1663         p.writeInt32(p_cur->isVoicePrivacy);
1664         writeStringToParcel(p, p_cur->number);
1665         p.writeInt32(p_cur->numberPresentation);
1666         writeStringToParcel(p, p_cur->name);
1667         p.writeInt32(p_cur->namePresentation);
1668         // Remove when partners upgrade to version 3
1669         if ((s_callbacks.version < 3) || (p_cur->uusInfo == NULL || p_cur->uusInfo->uusData == NULL)) {
1670             p.writeInt32(0); /* UUS Information is absent */
1671         } else {
1672             RIL_UUS_Info *uusInfo = p_cur->uusInfo;
1673             p.writeInt32(1); /* UUS Information is present */
1674             p.writeInt32(uusInfo->uusType);
1675             p.writeInt32(uusInfo->uusDcs);
1676             p.writeInt32(uusInfo->uusLength);
1677             p.write(uusInfo->uusData, uusInfo->uusLength);
1678         }
1679         appendPrintBuf("%s[id=%d,%s,toa=%d,",
1680             printBuf,
1681             p_cur->index,
1682             callStateToString(p_cur->state),
1683             p_cur->toa);
1684         appendPrintBuf("%s%s,%s,als=%d,%s,%s,",
1685             printBuf,
1686             (p_cur->isMpty)?"conf":"norm",
1687             (p_cur->isMT)?"mt":"mo",
1688             p_cur->als,
1689             (p_cur->isVoice)?"voc":"nonvoc",
1690             (p_cur->isVoicePrivacy)?"evp":"noevp");
1691         appendPrintBuf("%s%s,cli=%d,name='%s',%d]",
1692             printBuf,
1693             p_cur->number,
1694             p_cur->numberPresentation,
1695             p_cur->name,
1696             p_cur->namePresentation);
1697     }
1698     removeLastChar;
1699     closeResponse;
1700
1701     return 0;
1702 }
1703
1704 static int responseSMS(Parcel &p, void *response, size_t responselen) {
1705     if (response == NULL) {
1706         RLOGE("invalid response: NULL");
1707         return RIL_ERRNO_INVALID_RESPONSE;
1708     }
1709
1710     if (responselen != sizeof (RIL_SMS_Response) ) {
1711         RLOGE("invalid response length %d expected %d",
1712                 (int)responselen, (int)sizeof (RIL_SMS_Response));
1713         return RIL_ERRNO_INVALID_RESPONSE;
1714     }
1715
1716     RIL_SMS_Response *p_cur = (RIL_SMS_Response *) response;
1717
1718     p.writeInt32(p_cur->messageRef);
1719     writeStringToParcel(p, p_cur->ackPDU);
1720     p.writeInt32(p_cur->errorCode);
1721
1722     startResponse;
1723     appendPrintBuf("%s%d,%s,%d", printBuf, p_cur->messageRef,
1724         (char*)p_cur->ackPDU, p_cur->errorCode);
1725     closeResponse;
1726
1727     return 0;
1728 }
1729
1730 static int responseDataCallListV4(Parcel &p, void *response, size_t responselen)
1731 {
1732     if (response == NULL && responselen != 0) {
1733         RLOGE("invalid response: NULL");
1734         return RIL_ERRNO_INVALID_RESPONSE;
1735     }
1736
1737     if (responselen % sizeof(RIL_Data_Call_Response_v4) != 0) {
1738         RLOGE("invalid response length %d expected multiple of %d",
1739                 (int)responselen, (int)sizeof(RIL_Data_Call_Response_v4));
1740         return RIL_ERRNO_INVALID_RESPONSE;
1741     }
1742
1743     int num = responselen / sizeof(RIL_Data_Call_Response_v4);
1744     p.writeInt32(num);
1745
1746     RIL_Data_Call_Response_v4 *p_cur = (RIL_Data_Call_Response_v4 *) response;
1747     startResponse;
1748     int i;
1749     for (i = 0; i < num; i++) {
1750         p.writeInt32(p_cur[i].cid);
1751         p.writeInt32(p_cur[i].active);
1752         writeStringToParcel(p, p_cur[i].type);
1753         // apn is not used, so don't send.
1754         writeStringToParcel(p, p_cur[i].address);
1755         appendPrintBuf("%s[cid=%d,%s,%s,%s],", printBuf,
1756             p_cur[i].cid,
1757             (p_cur[i].active==0)?"down":"up",
1758             (char*)p_cur[i].type,
1759             (char*)p_cur[i].address);
1760     }
1761     removeLastChar;
1762     closeResponse;
1763
1764     return 0;
1765 }
1766
1767 static int responseDataCallList(Parcel &p, void *response, size_t responselen)
1768 {
1769     // Write version
1770     p.writeInt32(s_callbacks.version);
1771
1772     if (s_callbacks.version < 5) {
1773         return responseDataCallListV4(p, response, responselen);
1774     } else {
1775         if (response == NULL && responselen != 0) {
1776             RLOGE("invalid response: NULL");
1777             return RIL_ERRNO_INVALID_RESPONSE;
1778         }
1779
1780         if (responselen % sizeof(RIL_Data_Call_Response_v6) != 0) {
1781             RLOGE("invalid response length %d expected multiple of %d",
1782                     (int)responselen, (int)sizeof(RIL_Data_Call_Response_v6));
1783             return RIL_ERRNO_INVALID_RESPONSE;
1784         }
1785
1786         int num = responselen / sizeof(RIL_Data_Call_Response_v6);
1787         p.writeInt32(num);
1788
1789         RIL_Data_Call_Response_v6 *p_cur = (RIL_Data_Call_Response_v6 *) response;
1790         startResponse;
1791         int i;
1792         for (i = 0; i < num; i++) {
1793             p.writeInt32((int)p_cur[i].status);
1794             p.writeInt32(p_cur[i].suggestedRetryTime);
1795             p.writeInt32(p_cur[i].cid);
1796             p.writeInt32(p_cur[i].active);
1797             writeStringToParcel(p, p_cur[i].type);
1798             writeStringToParcel(p, p_cur[i].ifname);
1799             writeStringToParcel(p, p_cur[i].addresses);
1800             writeStringToParcel(p, p_cur[i].dnses);
1801             writeStringToParcel(p, p_cur[i].gateways);
1802             appendPrintBuf("%s[status=%d,retry=%d,cid=%d,%s,%s,%s,%s,%s,%s],", printBuf,
1803                 p_cur[i].status,
1804                 p_cur[i].suggestedRetryTime,
1805                 p_cur[i].cid,
1806                 (p_cur[i].active==0)?"down":"up",
1807                 (char*)p_cur[i].type,
1808                 (char*)p_cur[i].ifname,
1809                 (char*)p_cur[i].addresses,
1810                 (char*)p_cur[i].dnses,
1811                 (char*)p_cur[i].gateways);
1812         }
1813         removeLastChar;
1814         closeResponse;
1815     }
1816
1817     return 0;
1818 }
1819
1820 static int responseSetupDataCall(Parcel &p, void *response, size_t responselen)
1821 {
1822     if (s_callbacks.version < 5) {
1823         return responseStringsWithVersion(s_callbacks.version, p, response, responselen);
1824     } else {
1825         return responseDataCallList(p, response, responselen);
1826     }
1827 }
1828
1829 static int responseRaw(Parcel &p, void *response, size_t responselen) {
1830     if (response == NULL && responselen != 0) {
1831         RLOGE("invalid response: NULL with responselen != 0");
1832         return RIL_ERRNO_INVALID_RESPONSE;
1833     }
1834
1835     // The java code reads -1 size as null byte array
1836     if (response == NULL) {
1837         p.writeInt32(-1);
1838     } else {
1839         p.writeInt32(responselen);
1840         p.write(response, responselen);
1841     }
1842
1843     return 0;
1844 }
1845
1846
1847 static int responseSIM_IO(Parcel &p, void *response, size_t responselen) {
1848     if (response == NULL) {
1849         RLOGE("invalid response: NULL");
1850         return RIL_ERRNO_INVALID_RESPONSE;
1851     }
1852
1853     if (responselen != sizeof (RIL_SIM_IO_Response) ) {
1854         RLOGE("invalid response length was %d expected %d",
1855                 (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
1856         return RIL_ERRNO_INVALID_RESPONSE;
1857     }
1858
1859     RIL_SIM_IO_Response *p_cur = (RIL_SIM_IO_Response *) response;
1860     p.writeInt32(p_cur->sw1);
1861     p.writeInt32(p_cur->sw2);
1862     writeStringToParcel(p, p_cur->simResponse);
1863
1864     startResponse;
1865     appendPrintBuf("%ssw1=0x%X,sw2=0x%X,%s", printBuf, p_cur->sw1, p_cur->sw2,
1866         (char*)p_cur->simResponse);
1867     closeResponse;
1868
1869
1870     return 0;
1871 }
1872
1873 static int responseCallForwards(Parcel &p, void *response, size_t responselen) {
1874     int num;
1875
1876     if (response == NULL && responselen != 0) {
1877         RLOGE("invalid response: NULL");
1878         return RIL_ERRNO_INVALID_RESPONSE;
1879     }
1880
1881     if (responselen % sizeof(RIL_CallForwardInfo *) != 0) {
1882         RLOGE("invalid response length %d expected multiple of %d",
1883                 (int)responselen, (int)sizeof(RIL_CallForwardInfo *));
1884         return RIL_ERRNO_INVALID_RESPONSE;
1885     }
1886
1887     /* number of call info's */
1888     num = responselen / sizeof(RIL_CallForwardInfo *);
1889     p.writeInt32(num);
1890
1891     startResponse;
1892     for (int i = 0 ; i < num ; i++) {
1893         RIL_CallForwardInfo *p_cur = ((RIL_CallForwardInfo **) response)[i];
1894
1895         p.writeInt32(p_cur->status);
1896         p.writeInt32(p_cur->reason);
1897         p.writeInt32(p_cur->serviceClass);
1898         p.writeInt32(p_cur->toa);
1899         writeStringToParcel(p, p_cur->number);
1900         p.writeInt32(p_cur->timeSeconds);
1901         appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
1902             (p_cur->status==1)?"enable":"disable",
1903             p_cur->reason, p_cur->serviceClass, p_cur->toa,
1904             (char*)p_cur->number,
1905             p_cur->timeSeconds);
1906     }
1907     removeLastChar;
1908     closeResponse;
1909
1910     return 0;
1911 }
1912
1913 static int responseSsn(Parcel &p, void *response, size_t responselen) {
1914     if (response == NULL) {
1915         RLOGE("invalid response: NULL");
1916         return RIL_ERRNO_INVALID_RESPONSE;
1917     }
1918
1919     if (responselen != sizeof(RIL_SuppSvcNotification)) {
1920         RLOGE("invalid response length was %d expected %d",
1921                 (int)responselen, (int)sizeof (RIL_SuppSvcNotification));
1922         return RIL_ERRNO_INVALID_RESPONSE;
1923     }
1924
1925     RIL_SuppSvcNotification *p_cur = (RIL_SuppSvcNotification *) response;
1926     p.writeInt32(p_cur->notificationType);
1927     p.writeInt32(p_cur->code);
1928     p.writeInt32(p_cur->index);
1929     p.writeInt32(p_cur->type);
1930     writeStringToParcel(p, p_cur->number);
1931
1932     startResponse;
1933     appendPrintBuf("%s%s,code=%d,id=%d,type=%d,%s", printBuf,
1934         (p_cur->notificationType==0)?"mo":"mt",
1935          p_cur->code, p_cur->index, p_cur->type,
1936         (char*)p_cur->number);
1937     closeResponse;
1938
1939     return 0;
1940 }
1941
1942 static int responseCellList(Parcel &p, void *response, size_t responselen) {
1943     int num;
1944
1945     if (response == NULL && responselen != 0) {
1946         RLOGE("invalid response: NULL");
1947         return RIL_ERRNO_INVALID_RESPONSE;
1948     }
1949
1950     if (responselen % sizeof (RIL_NeighboringCell *) != 0) {
1951         RLOGE("invalid response length %d expected multiple of %d\n",
1952             (int)responselen, (int)sizeof (RIL_NeighboringCell *));
1953         return RIL_ERRNO_INVALID_RESPONSE;
1954     }
1955
1956     startResponse;
1957     /* number of records */
1958     num = responselen / sizeof(RIL_NeighboringCell *);
1959     p.writeInt32(num);
1960
1961     for (int i = 0 ; i < num ; i++) {
1962         RIL_NeighboringCell *p_cur = ((RIL_NeighboringCell **) response)[i];
1963
1964         p.writeInt32(p_cur->rssi);
1965         writeStringToParcel (p, p_cur->cid);
1966
1967         appendPrintBuf("%s[cid=%s,rssi=%d],", printBuf,
1968             p_cur->cid, p_cur->rssi);
1969     }
1970     removeLastChar;
1971     closeResponse;
1972
1973     return 0;
1974 }
1975
1976 /**
1977  * Marshall the signalInfoRecord into the parcel if it exists.
1978  */
1979 static void marshallSignalInfoRecord(Parcel &p,
1980             RIL_CDMA_SignalInfoRecord &p_signalInfoRecord) {
1981     p.writeInt32(p_signalInfoRecord.isPresent);
1982     p.writeInt32(p_signalInfoRecord.signalType);
1983     p.writeInt32(p_signalInfoRecord.alertPitch);
1984     p.writeInt32(p_signalInfoRecord.signal);
1985 }
1986
1987 static int responseCdmaInformationRecords(Parcel &p,
1988             void *response, size_t responselen) {
1989     int num;
1990     char* string8 = NULL;
1991     int buffer_lenght;
1992     RIL_CDMA_InformationRecord *infoRec;
1993
1994     if (response == NULL && responselen != 0) {
1995         RLOGE("invalid response: NULL");
1996         return RIL_ERRNO_INVALID_RESPONSE;
1997     }
1998
1999     if (responselen != sizeof (RIL_CDMA_InformationRecords)) {
2000         RLOGE("invalid response length %d expected multiple of %d\n",
2001             (int)responselen, (int)sizeof (RIL_CDMA_InformationRecords *));
2002         return RIL_ERRNO_INVALID_RESPONSE;
2003     }
2004
2005     RIL_CDMA_InformationRecords *p_cur =
2006                              (RIL_CDMA_InformationRecords *) response;
2007     num = MIN(p_cur->numberOfInfoRecs, RIL_CDMA_MAX_NUMBER_OF_INFO_RECS);
2008
2009     startResponse;
2010     p.writeInt32(num);
2011
2012     for (int i = 0 ; i < num ; i++) {
2013         infoRec = &p_cur->infoRec[i];
2014         p.writeInt32(infoRec->name);
2015         switch (infoRec->name) {
2016             case RIL_CDMA_DISPLAY_INFO_REC:
2017             case RIL_CDMA_EXTENDED_DISPLAY_INFO_REC:
2018                 if (infoRec->rec.display.alpha_len >
2019                                          CDMA_ALPHA_INFO_BUFFER_LENGTH) {
2020                     RLOGE("invalid display info response length %d \
2021                           expected not more than %d\n",
2022                          (int)infoRec->rec.display.alpha_len,
2023                          CDMA_ALPHA_INFO_BUFFER_LENGTH);
2024                     return RIL_ERRNO_INVALID_RESPONSE;
2025                 }
2026                 string8 = (char*) malloc((infoRec->rec.display.alpha_len + 1)
2027                                                              * sizeof(char) );
2028                 for (int i = 0 ; i < infoRec->rec.display.alpha_len ; i++) {
2029                     string8[i] = infoRec->rec.display.alpha_buf[i];
2030                 }
2031                 string8[(int)infoRec->rec.display.alpha_len] = '\0';
2032                 writeStringToParcel(p, (const char*)string8);
2033                 free(string8);
2034                 string8 = NULL;
2035                 break;
2036             case RIL_CDMA_CALLED_PARTY_NUMBER_INFO_REC:
2037             case RIL_CDMA_CALLING_PARTY_NUMBER_INFO_REC:
2038             case RIL_CDMA_CONNECTED_NUMBER_INFO_REC:
2039                 if (infoRec->rec.number.len > CDMA_NUMBER_INFO_BUFFER_LENGTH) {
2040                     RLOGE("invalid display info response length %d \
2041                           expected not more than %d\n",
2042                          (int)infoRec->rec.number.len,
2043                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
2044                     return RIL_ERRNO_INVALID_RESPONSE;
2045                 }
2046                 string8 = (char*) malloc((infoRec->rec.number.len + 1)
2047                                                              * sizeof(char) );
2048                 for (int i = 0 ; i < infoRec->rec.number.len; i++) {
2049                     string8[i] = infoRec->rec.number.buf[i];
2050                 }
2051                 string8[(int)infoRec->rec.number.len] = '\0';
2052                 writeStringToParcel(p, (const char*)string8);
2053                 free(string8);
2054                 string8 = NULL;
2055                 p.writeInt32(infoRec->rec.number.number_type);
2056                 p.writeInt32(infoRec->rec.number.number_plan);
2057                 p.writeInt32(infoRec->rec.number.pi);
2058                 p.writeInt32(infoRec->rec.number.si);
2059                 break;
2060             case RIL_CDMA_SIGNAL_INFO_REC:
2061                 p.writeInt32(infoRec->rec.signal.isPresent);
2062                 p.writeInt32(infoRec->rec.signal.signalType);
2063                 p.writeInt32(infoRec->rec.signal.alertPitch);
2064                 p.writeInt32(infoRec->rec.signal.signal);
2065
2066                 appendPrintBuf("%sisPresent=%X, signalType=%X, \
2067                                 alertPitch=%X, signal=%X, ",
2068                    printBuf, (int)infoRec->rec.signal.isPresent,
2069                    (int)infoRec->rec.signal.signalType,
2070                    (int)infoRec->rec.signal.alertPitch,
2071                    (int)infoRec->rec.signal.signal);
2072                 removeLastChar;
2073                 break;
2074             case RIL_CDMA_REDIRECTING_NUMBER_INFO_REC:
2075                 if (infoRec->rec.redir.redirectingNumber.len >
2076                                               CDMA_NUMBER_INFO_BUFFER_LENGTH) {
2077                     RLOGE("invalid display info response length %d \
2078                           expected not more than %d\n",
2079                          (int)infoRec->rec.redir.redirectingNumber.len,
2080                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
2081                     return RIL_ERRNO_INVALID_RESPONSE;
2082                 }
2083                 string8 = (char*) malloc((infoRec->rec.redir.redirectingNumber
2084                                           .len + 1) * sizeof(char) );
2085                 for (int i = 0;
2086                          i < infoRec->rec.redir.redirectingNumber.len;
2087                          i++) {
2088                     string8[i] = infoRec->rec.redir.redirectingNumber.buf[i];
2089                 }
2090                 string8[(int)infoRec->rec.redir.redirectingNumber.len] = '\0';
2091                 writeStringToParcel(p, (const char*)string8);
2092                 free(string8);
2093                 string8 = NULL;
2094                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_type);
2095                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_plan);
2096                 p.writeInt32(infoRec->rec.redir.redirectingNumber.pi);
2097                 p.writeInt32(infoRec->rec.redir.redirectingNumber.si);
2098                 p.writeInt32(infoRec->rec.redir.redirectingReason);
2099                 break;
2100             case RIL_CDMA_LINE_CONTROL_INFO_REC:
2101                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPolarityIncluded);
2102                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlToggle);
2103                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlReverse);
2104                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPowerDenial);
2105
2106                 appendPrintBuf("%slineCtrlPolarityIncluded=%d, \
2107                                 lineCtrlToggle=%d, lineCtrlReverse=%d, \
2108                                 lineCtrlPowerDenial=%d, ", printBuf,
2109                        (int)infoRec->rec.lineCtrl.lineCtrlPolarityIncluded,
2110                        (int)infoRec->rec.lineCtrl.lineCtrlToggle,
2111                        (int)infoRec->rec.lineCtrl.lineCtrlReverse,
2112                        (int)infoRec->rec.lineCtrl.lineCtrlPowerDenial);
2113                 removeLastChar;
2114                 break;
2115             case RIL_CDMA_T53_CLIR_INFO_REC:
2116                 p.writeInt32((int)(infoRec->rec.clir.cause));
2117
2118                 appendPrintBuf("%scause%d", printBuf, infoRec->rec.clir.cause);
2119                 removeLastChar;
2120                 break;
2121             case RIL_CDMA_T53_AUDIO_CONTROL_INFO_REC:
2122                 p.writeInt32(infoRec->rec.audioCtrl.upLink);
2123                 p.writeInt32(infoRec->rec.audioCtrl.downLink);
2124
2125                 appendPrintBuf("%supLink=%d, downLink=%d, ", printBuf,
2126                         infoRec->rec.audioCtrl.upLink,
2127                         infoRec->rec.audioCtrl.downLink);
2128                 removeLastChar;
2129                 break;
2130             case RIL_CDMA_T53_RELEASE_INFO_REC:
2131                 // TODO(Moto): See David Krause, he has the answer:)
2132                 RLOGE("RIL_CDMA_T53_RELEASE_INFO_REC: return INVALID_RESPONSE");
2133                 return RIL_ERRNO_INVALID_RESPONSE;
2134             default:
2135                 RLOGE("Incorrect name value");
2136                 return RIL_ERRNO_INVALID_RESPONSE;
2137         }
2138     }
2139     closeResponse;
2140
2141     return 0;
2142 }
2143
2144 static int responseRilSignalStrength(Parcel &p,
2145                     void *response, size_t responselen) {
2146     if (response == NULL && responselen != 0) {
2147         RLOGE("invalid response: NULL");
2148         return RIL_ERRNO_INVALID_RESPONSE;
2149     }
2150
2151     if (responselen >= sizeof (RIL_SignalStrength_v5)) {
2152         RIL_SignalStrength_v6 *p_cur = ((RIL_SignalStrength_v6 *) response);
2153
2154         p.writeInt32(p_cur->GW_SignalStrength.signalStrength);
2155         p.writeInt32(p_cur->GW_SignalStrength.bitErrorRate);
2156         p.writeInt32(p_cur->CDMA_SignalStrength.dbm);
2157         p.writeInt32(p_cur->CDMA_SignalStrength.ecio);
2158         p.writeInt32(p_cur->EVDO_SignalStrength.dbm);
2159         p.writeInt32(p_cur->EVDO_SignalStrength.ecio);
2160         p.writeInt32(p_cur->EVDO_SignalStrength.signalNoiseRatio);
2161         if (responselen >= sizeof (RIL_SignalStrength_v6)) {
2162             /*
2163              * Fixup LTE for backwards compatibility
2164              */
2165             if (s_callbacks.version <= 6) {
2166                 // signalStrength: -1 -> 99
2167                 if (p_cur->LTE_SignalStrength.signalStrength == -1) {
2168                     p_cur->LTE_SignalStrength.signalStrength = 99;
2169                 }
2170                 // rsrp: -1 -> INT_MAX all other negative value to positive.
2171                 // So remap here
2172                 if (p_cur->LTE_SignalStrength.rsrp == -1) {
2173                     p_cur->LTE_SignalStrength.rsrp = INT_MAX;
2174                 } else if (p_cur->LTE_SignalStrength.rsrp < -1) {
2175                     p_cur->LTE_SignalStrength.rsrp = -p_cur->LTE_SignalStrength.rsrp;
2176                 }
2177                 // rsrq: -1 -> INT_MAX
2178                 if (p_cur->LTE_SignalStrength.rsrq == -1) {
2179                     p_cur->LTE_SignalStrength.rsrq = INT_MAX;
2180                 }
2181                 // Not remapping rssnr is already using INT_MAX
2182
2183                 // cqi: -1 -> INT_MAX
2184                 if (p_cur->LTE_SignalStrength.cqi == -1) {
2185                     p_cur->LTE_SignalStrength.cqi = INT_MAX;
2186                 }
2187             }
2188             p.writeInt32(p_cur->LTE_SignalStrength.signalStrength);
2189             p.writeInt32(p_cur->LTE_SignalStrength.rsrp);
2190             p.writeInt32(p_cur->LTE_SignalStrength.rsrq);
2191             p.writeInt32(p_cur->LTE_SignalStrength.rssnr);
2192             p.writeInt32(p_cur->LTE_SignalStrength.cqi);
2193         } else {
2194             p.writeInt32(99);
2195             p.writeInt32(INT_MAX);
2196             p.writeInt32(INT_MAX);
2197             p.writeInt32(INT_MAX);
2198             p.writeInt32(INT_MAX);
2199         }
2200
2201         startResponse;
2202         appendPrintBuf("%s[signalStrength=%d,bitErrorRate=%d,\
2203                 CDMA_SS.dbm=%d,CDMA_SSecio=%d,\
2204                 EVDO_SS.dbm=%d,EVDO_SS.ecio=%d,\
2205                 EVDO_SS.signalNoiseRatio=%d,\
2206                 LTE_SS.signalStrength=%d,LTE_SS.rsrp=%d,LTE_SS.rsrq=%d,\
2207                 LTE_SS.rssnr=%d,LTE_SS.cqi=%d]",
2208                 printBuf,
2209                 p_cur->GW_SignalStrength.signalStrength,
2210                 p_cur->GW_SignalStrength.bitErrorRate,
2211                 p_cur->CDMA_SignalStrength.dbm,
2212                 p_cur->CDMA_SignalStrength.ecio,
2213                 p_cur->EVDO_SignalStrength.dbm,
2214                 p_cur->EVDO_SignalStrength.ecio,
2215                 p_cur->EVDO_SignalStrength.signalNoiseRatio,
2216                 p_cur->LTE_SignalStrength.signalStrength,
2217                 p_cur->LTE_SignalStrength.rsrp,
2218                 p_cur->LTE_SignalStrength.rsrq,
2219                 p_cur->LTE_SignalStrength.rssnr,
2220                 p_cur->LTE_SignalStrength.cqi);
2221         closeResponse;
2222
2223     } else {
2224         RLOGE("invalid response length");
2225         return RIL_ERRNO_INVALID_RESPONSE;
2226     }
2227
2228     return 0;
2229 }
2230
2231 static int responseCallRing(Parcel &p, void *response, size_t responselen) {
2232     if ((response == NULL) || (responselen == 0)) {
2233         return responseVoid(p, response, responselen);
2234     } else {
2235         return responseCdmaSignalInfoRecord(p, response, responselen);
2236     }
2237 }
2238
2239 static int responseCdmaSignalInfoRecord(Parcel &p, void *response, size_t responselen) {
2240     if (response == NULL || responselen == 0) {
2241         RLOGE("invalid response: NULL");
2242         return RIL_ERRNO_INVALID_RESPONSE;
2243     }
2244
2245     if (responselen != sizeof (RIL_CDMA_SignalInfoRecord)) {
2246         RLOGE("invalid response length %d expected sizeof (RIL_CDMA_SignalInfoRecord) of %d\n",
2247             (int)responselen, (int)sizeof (RIL_CDMA_SignalInfoRecord));
2248         return RIL_ERRNO_INVALID_RESPONSE;
2249     }
2250
2251     startResponse;
2252
2253     RIL_CDMA_SignalInfoRecord *p_cur = ((RIL_CDMA_SignalInfoRecord *) response);
2254     marshallSignalInfoRecord(p, *p_cur);
2255
2256     appendPrintBuf("%s[isPresent=%d,signalType=%d,alertPitch=%d\
2257               signal=%d]",
2258               printBuf,
2259               p_cur->isPresent,
2260               p_cur->signalType,
2261               p_cur->alertPitch,
2262               p_cur->signal);
2263
2264     closeResponse;
2265     return 0;
2266 }
2267
2268 static int responseCdmaCallWaiting(Parcel &p, void *response,
2269             size_t responselen) {
2270     if (response == NULL && responselen != 0) {
2271         RLOGE("invalid response: NULL");
2272         return RIL_ERRNO_INVALID_RESPONSE;
2273     }
2274
2275     if (responselen < sizeof(RIL_CDMA_CallWaiting_v6)) {
2276         RLOGW("Upgrade to ril version %d\n", RIL_VERSION);
2277     }
2278
2279     RIL_CDMA_CallWaiting_v6 *p_cur = ((RIL_CDMA_CallWaiting_v6 *) response);
2280
2281     writeStringToParcel(p, p_cur->number);
2282     p.writeInt32(p_cur->numberPresentation);
2283     writeStringToParcel(p, p_cur->name);
2284     marshallSignalInfoRecord(p, p_cur->signalInfoRecord);
2285
2286     if (responselen >= sizeof(RIL_CDMA_CallWaiting_v6)) {
2287         p.writeInt32(p_cur->number_type);
2288         p.writeInt32(p_cur->number_plan);
2289     } else {
2290         p.writeInt32(0);
2291         p.writeInt32(0);
2292     }
2293
2294     startResponse;
2295     appendPrintBuf("%snumber=%s,numberPresentation=%d, name=%s,\
2296             signalInfoRecord[isPresent=%d,signalType=%d,alertPitch=%d\
2297             signal=%d,number_type=%d,number_plan=%d]",
2298             printBuf,
2299             p_cur->number,
2300             p_cur->numberPresentation,
2301             p_cur->name,
2302             p_cur->signalInfoRecord.isPresent,
2303             p_cur->signalInfoRecord.signalType,
2304             p_cur->signalInfoRecord.alertPitch,
2305             p_cur->signalInfoRecord.signal,
2306             p_cur->number_type,
2307             p_cur->number_plan);
2308     closeResponse;
2309
2310     return 0;
2311 }
2312
2313 static int responseSimRefresh(Parcel &p, void *response, size_t responselen) {
2314     if (response == NULL && responselen != 0) {
2315         RLOGE("responseSimRefresh: invalid response: NULL");
2316         return RIL_ERRNO_INVALID_RESPONSE;
2317     }
2318
2319     startResponse;
2320     if (s_callbacks.version == 7) {
2321         RIL_SimRefreshResponse_v7 *p_cur = ((RIL_SimRefreshResponse_v7 *) response);
2322         p.writeInt32(p_cur->result);
2323         p.writeInt32(p_cur->ef_id);
2324         writeStringToParcel(p, p_cur->aid);
2325
2326         appendPrintBuf("%sresult=%d, ef_id=%d, aid=%s",
2327                 printBuf,
2328                 p_cur->result,
2329                 p_cur->ef_id,
2330                 p_cur->aid);
2331     } else {
2332         int *p_cur = ((int *) response);
2333         p.writeInt32(p_cur[0]);
2334         p.writeInt32(p_cur[1]);
2335         writeStringToParcel(p, NULL);
2336
2337         appendPrintBuf("%sresult=%d, ef_id=%d",
2338                 printBuf,
2339                 p_cur[0],
2340                 p_cur[1]);
2341     }
2342     closeResponse;
2343
2344     return 0;
2345 }
2346
2347 static int responseCellInfoList(Parcel &p, void *response, size_t responselen)
2348 {
2349     if (response == NULL && responselen != 0) {
2350         RLOGE("invalid response: NULL");
2351         return RIL_ERRNO_INVALID_RESPONSE;
2352     }
2353
2354     if (responselen % sizeof(RIL_CellInfo) != 0) {
2355         RLOGE("invalid response length %d expected multiple of %d",
2356                 (int)responselen, (int)sizeof(RIL_CellInfo));
2357         return RIL_ERRNO_INVALID_RESPONSE;
2358     }
2359
2360     int num = responselen / sizeof(RIL_CellInfo);
2361     p.writeInt32(num);
2362
2363     RIL_CellInfo *p_cur = (RIL_CellInfo *) response;
2364     startResponse;
2365     int i;
2366     for (i = 0; i < num; i++) {
2367         appendPrintBuf("%s[%d: type=%d,registered=%d,timeStampType=%d,timeStamp=%lld", printBuf, i,
2368             p_cur->cellInfoType, p_cur->registered, p_cur->timeStampType, p_cur->timeStamp);
2369         p.writeInt32((int)p_cur->cellInfoType);
2370         p.writeInt32(p_cur->registered);
2371         p.writeInt32(p_cur->timeStampType);
2372         p.writeInt64(p_cur->timeStamp);
2373         switch(p_cur->cellInfoType) {
2374             case RIL_CELL_INFO_TYPE_GSM: {
2375                 appendPrintBuf("%s GSM id: mcc=%d,mnc=%d,lac=%d,cid=%d,", printBuf,
2376                     p_cur->CellInfo.gsm.cellIdentityGsm.mcc,
2377                     p_cur->CellInfo.gsm.cellIdentityGsm.mnc,
2378                     p_cur->CellInfo.gsm.cellIdentityGsm.lac,
2379                     p_cur->CellInfo.gsm.cellIdentityGsm.cid);
2380                 appendPrintBuf("%s gsmSS: ss=%d,ber=%d],", printBuf,
2381                     p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength,
2382                     p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
2383
2384                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
2385                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
2386                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
2387                 p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
2388                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
2389                 p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
2390                 break;
2391             }
2392             case RIL_CELL_INFO_TYPE_WCDMA: {
2393                 appendPrintBuf("%s WCDMA id: mcc=%d,mnc=%d,lac=%d,cid=%d,psc=%d,", printBuf,
2394                     p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc,
2395                     p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc,
2396                     p_cur->CellInfo.wcdma.cellIdentityWcdma.lac,
2397                     p_cur->CellInfo.wcdma.cellIdentityWcdma.cid,
2398                     p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
2399                 appendPrintBuf("%s wcdmaSS: ss=%d,ber=%d],", printBuf,
2400                     p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength,
2401                     p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
2402
2403                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc);
2404                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc);
2405                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.lac);
2406                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.cid);
2407                 p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
2408                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
2409                 p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
2410                 break;
2411             }
2412             case RIL_CELL_INFO_TYPE_CDMA: {
2413                 appendPrintBuf("%s CDMA id: nId=%d,sId=%d,bsId=%d,long=%d,lat=%d", printBuf,
2414                     p_cur->CellInfo.cdma.cellIdentityCdma.networkId,
2415                     p_cur->CellInfo.cdma.cellIdentityCdma.systemId,
2416                     p_cur->CellInfo.cdma.cellIdentityCdma.basestationId,
2417                     p_cur->CellInfo.cdma.cellIdentityCdma.longitude,
2418                     p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
2419
2420                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
2421                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
2422                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
2423                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
2424                 p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
2425
2426                 appendPrintBuf("%s cdmaSS: dbm=%d ecio=%d evdoSS: dbm=%d,ecio=%d,snr=%d", printBuf,
2427                     p_cur->CellInfo.cdma.signalStrengthCdma.dbm,
2428                     p_cur->CellInfo.cdma.signalStrengthCdma.ecio,
2429                     p_cur->CellInfo.cdma.signalStrengthEvdo.dbm,
2430                     p_cur->CellInfo.cdma.signalStrengthEvdo.ecio,
2431                     p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
2432
2433                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
2434                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
2435                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
2436                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
2437                 p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
2438                 break;
2439             }
2440             case RIL_CELL_INFO_TYPE_LTE: {
2441                 appendPrintBuf("%s LTE id: mcc=%d,mnc=%d,ci=%d,pci=%d,tac=%d", printBuf,
2442                     p_cur->CellInfo.lte.cellIdentityLte.mcc,
2443                     p_cur->CellInfo.lte.cellIdentityLte.mnc,
2444                     p_cur->CellInfo.lte.cellIdentityLte.ci,
2445                     p_cur->CellInfo.lte.cellIdentityLte.pci,
2446                     p_cur->CellInfo.lte.cellIdentityLte.tac);
2447
2448                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
2449                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
2450                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
2451                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
2452                 p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
2453
2454                 appendPrintBuf("%s lteSS: ss=%d,rsrp=%d,rsrq=%d,rssnr=%d,cqi=%d,ta=%d", printBuf,
2455                     p_cur->CellInfo.lte.signalStrengthLte.signalStrength,
2456                     p_cur->CellInfo.lte.signalStrengthLte.rsrp,
2457                     p_cur->CellInfo.lte.signalStrengthLte.rsrq,
2458                     p_cur->CellInfo.lte.signalStrengthLte.rssnr,
2459                     p_cur->CellInfo.lte.signalStrengthLte.cqi,
2460                     p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
2461                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
2462                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
2463                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
2464                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
2465                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
2466                 p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
2467                 break;
2468             }
2469         }
2470         p_cur += 1;
2471     }
2472     removeLastChar;
2473     closeResponse;
2474
2475     return 0;
2476 }
2477
2478 static void triggerEvLoop() {
2479     int ret;
2480     if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
2481         /* trigger event loop to wakeup. No reason to do this,
2482          * if we're in the event loop thread */
2483          do {
2484             ret = write (s_fdWakeupWrite, " ", 1);
2485          } while (ret < 0 && errno == EINTR);
2486     }
2487 }
2488
2489 static void rilEventAddWakeup(struct ril_event *ev) {
2490     ril_event_add(ev);
2491     triggerEvLoop();
2492 }
2493
2494 static void sendSimStatusAppInfo(Parcel &p, int num_apps, RIL_AppStatus appStatus[]) {
2495         p.writeInt32(num_apps);
2496         startResponse;
2497         for (int i = 0; i < num_apps; i++) {
2498             p.writeInt32(appStatus[i].app_type);
2499             p.writeInt32(appStatus[i].app_state);
2500             p.writeInt32(appStatus[i].perso_substate);
2501             writeStringToParcel(p, (const char*)(appStatus[i].aid_ptr));
2502             writeStringToParcel(p, (const char*)
2503                                           (appStatus[i].app_label_ptr));
2504             p.writeInt32(appStatus[i].pin1_replaced);
2505             p.writeInt32(appStatus[i].pin1);
2506             p.writeInt32(appStatus[i].pin2);
2507             appendPrintBuf("%s[app_type=%d,app_state=%d,perso_substate=%d,\
2508                     aid_ptr=%s,app_label_ptr=%s,pin1_replaced=%d,pin1=%d,pin2=%d],",
2509                     printBuf,
2510                     appStatus[i].app_type,
2511                     appStatus[i].app_state,
2512                     appStatus[i].perso_substate,
2513                     appStatus[i].aid_ptr,
2514                     appStatus[i].app_label_ptr,
2515                     appStatus[i].pin1_replaced,
2516                     appStatus[i].pin1,
2517                     appStatus[i].pin2);
2518         }
2519         closeResponse;
2520 }
2521
2522 static int responseSimStatus(Parcel &p, void *response, size_t responselen) {
2523     int i;
2524
2525     if (response == NULL && responselen != 0) {
2526         RLOGE("invalid response: NULL");
2527         return RIL_ERRNO_INVALID_RESPONSE;
2528     }
2529
2530     if (responselen == sizeof (RIL_CardStatus_v6)) {
2531         RIL_CardStatus_v6 *p_cur = ((RIL_CardStatus_v6 *) response);
2532
2533         p.writeInt32(p_cur->card_state);
2534         p.writeInt32(p_cur->universal_pin_state);
2535         p.writeInt32(p_cur->gsm_umts_subscription_app_index);
2536         p.writeInt32(p_cur->cdma_subscription_app_index);
2537         p.writeInt32(p_cur->ims_subscription_app_index);
2538
2539         sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
2540     } else if (responselen == sizeof (RIL_CardStatus_v5)) {
2541         RIL_CardStatus_v5 *p_cur = ((RIL_CardStatus_v5 *) response);
2542
2543         p.writeInt32(p_cur->card_state);
2544         p.writeInt32(p_cur->universal_pin_state);
2545         p.writeInt32(p_cur->gsm_umts_subscription_app_index);
2546         p.writeInt32(p_cur->cdma_subscription_app_index);
2547         p.writeInt32(-1);
2548
2549         sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
2550     } else {
2551         RLOGE("responseSimStatus: A RilCardStatus_v6 or _v5 expected\n");
2552         return RIL_ERRNO_INVALID_RESPONSE;
2553     }
2554
2555     return 0;
2556 }
2557
2558 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2559     int num = responselen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
2560     p.writeInt32(num);
2561
2562     startResponse;
2563     RIL_GSM_BroadcastSmsConfigInfo **p_cur =
2564                 (RIL_GSM_BroadcastSmsConfigInfo **) response;
2565     for (int i = 0; i < num; i++) {
2566         p.writeInt32(p_cur[i]->fromServiceId);
2567         p.writeInt32(p_cur[i]->toServiceId);
2568         p.writeInt32(p_cur[i]->fromCodeScheme);
2569         p.writeInt32(p_cur[i]->toCodeScheme);
2570         p.writeInt32(p_cur[i]->selected);
2571
2572         appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId=%d, \
2573                 fromCodeScheme=%d, toCodeScheme=%d, selected =%d]",
2574                 printBuf, i, p_cur[i]->fromServiceId, p_cur[i]->toServiceId,
2575                 p_cur[i]->fromCodeScheme, p_cur[i]->toCodeScheme,
2576                 p_cur[i]->selected);
2577     }
2578     closeResponse;
2579
2580     return 0;
2581 }
2582
2583 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2584     RIL_CDMA_BroadcastSmsConfigInfo **p_cur =
2585                (RIL_CDMA_BroadcastSmsConfigInfo **) response;
2586
2587     int num = responselen / sizeof (RIL_CDMA_BroadcastSmsConfigInfo *);
2588     p.writeInt32(num);
2589
2590     startResponse;
2591     for (int i = 0 ; i < num ; i++ ) {
2592         p.writeInt32(p_cur[i]->service_category);
2593         p.writeInt32(p_cur[i]->language);
2594         p.writeInt32(p_cur[i]->selected);
2595
2596         appendPrintBuf("%s [%d: srvice_category=%d, language =%d, \
2597               selected =%d], ",
2598               printBuf, i, p_cur[i]->service_category, p_cur[i]->language,
2599               p_cur[i]->selected);
2600     }
2601     closeResponse;
2602
2603     return 0;
2604 }
2605
2606 static int responseCdmaSms(Parcel &p, void *response, size_t responselen) {
2607     int num;
2608     int digitCount;
2609     int digitLimit;
2610     uint8_t uct;
2611     void* dest;
2612
2613     RLOGD("Inside responseCdmaSms");
2614
2615     if (response == NULL && responselen != 0) {
2616         RLOGE("invalid response: NULL");
2617         return RIL_ERRNO_INVALID_RESPONSE;
2618     }
2619
2620     if (responselen != sizeof(RIL_CDMA_SMS_Message)) {
2621         RLOGE("invalid response length was %d expected %d",
2622                 (int)responselen, (int)sizeof(RIL_CDMA_SMS_Message));
2623         return RIL_ERRNO_INVALID_RESPONSE;
2624     }
2625
2626     RIL_CDMA_SMS_Message *p_cur = (RIL_CDMA_SMS_Message *) response;
2627     p.writeInt32(p_cur->uTeleserviceID);
2628     p.write(&(p_cur->bIsServicePresent),sizeof(uct));
2629     p.writeInt32(p_cur->uServicecategory);
2630     p.writeInt32(p_cur->sAddress.digit_mode);
2631     p.writeInt32(p_cur->sAddress.number_mode);
2632     p.writeInt32(p_cur->sAddress.number_type);
2633     p.writeInt32(p_cur->sAddress.number_plan);
2634     p.write(&(p_cur->sAddress.number_of_digits), sizeof(uct));
2635     digitLimit= MIN((p_cur->sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
2636     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2637         p.write(&(p_cur->sAddress.digits[digitCount]),sizeof(uct));
2638     }
2639
2640     p.writeInt32(p_cur->sSubAddress.subaddressType);
2641     p.write(&(p_cur->sSubAddress.odd),sizeof(uct));
2642     p.write(&(p_cur->sSubAddress.number_of_digits),sizeof(uct));
2643     digitLimit= MIN((p_cur->sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
2644     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2645         p.write(&(p_cur->sSubAddress.digits[digitCount]),sizeof(uct));
2646     }
2647
2648     digitLimit= MIN((p_cur->uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
2649     p.writeInt32(p_cur->uBearerDataLen);
2650     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2651        p.write(&(p_cur->aBearerData[digitCount]), sizeof(uct));
2652     }
2653
2654     startResponse;
2655     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
2656             sAddress.digit_mode=%d, sAddress.number_mode=%d, sAddress.number_type=%d, ",
2657             printBuf, p_cur->uTeleserviceID,p_cur->bIsServicePresent,p_cur->uServicecategory,
2658             p_cur->sAddress.digit_mode, p_cur->sAddress.number_mode,p_cur->sAddress.number_type);
2659     closeResponse;
2660
2661     return 0;
2662 }
2663
2664 /**
2665  * A write on the wakeup fd is done just to pop us out of select()
2666  * We empty the buffer here and then ril_event will reset the timers on the
2667  * way back down
2668  */
2669 static void processWakeupCallback(int fd, short flags, void *param) {
2670     char buff[16];
2671     int ret;
2672
2673     RLOGV("processWakeupCallback");
2674
2675     /* empty our wakeup socket out */
2676     do {
2677         ret = read(s_fdWakeupRead, &buff, sizeof(buff));
2678     } while (ret > 0 || (ret < 0 && errno == EINTR));
2679 }
2680
2681 static void onCommandsSocketClosed() {
2682     int ret;
2683     RequestInfo *p_cur;
2684
2685     /* mark pending requests as "cancelled" so we dont report responses */
2686
2687     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
2688     assert (ret == 0);
2689
2690     p_cur = s_pendingRequests;
2691
2692     for (p_cur = s_pendingRequests
2693             ; p_cur != NULL
2694             ; p_cur  = p_cur->p_next
2695     ) {
2696         p_cur->cancelled = 1;
2697     }
2698
2699     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
2700     assert (ret == 0);
2701 }
2702
2703 static void processCommandsCallback(int fd, short flags, void *param) {
2704     RecordStream *p_rs;
2705     void *p_record;
2706     size_t recordlen;
2707     int ret;
2708
2709     assert(fd == s_fdCommand);
2710
2711     p_rs = (RecordStream *)param;
2712
2713     for (;;) {
2714         /* loop until EAGAIN/EINTR, end of stream, or other error */
2715         ret = record_stream_get_next(p_rs, &p_record, &recordlen);
2716
2717         if (ret == 0 && p_record == NULL) {
2718             /* end-of-stream */
2719             break;
2720         } else if (ret < 0) {
2721             break;
2722         } else if (ret == 0) { /* && p_record != NULL */
2723             processCommandBuffer(p_record, recordlen);
2724         }
2725     }
2726
2727     if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
2728         /* fatal error or end-of-stream */
2729         if (ret != 0) {
2730             RLOGE("error on reading command socket errno:%d\n", errno);
2731         } else {
2732             RLOGW("EOS.  Closing command socket.");
2733         }
2734
2735         close(s_fdCommand);
2736         s_fdCommand = -1;
2737
2738         ril_event_del(&s_commands_event);
2739
2740         record_stream_free(p_rs);
2741
2742         /* start listening for new connections again */
2743         rilEventAddWakeup(&s_listen_event);
2744
2745         onCommandsSocketClosed();
2746     }
2747 }
2748
2749
2750 static void onNewCommandConnect() {
2751     // Inform we are connected and the ril version
2752     int rilVer = s_callbacks.version;
2753     RIL_onUnsolicitedResponse(RIL_UNSOL_RIL_CONNECTED,
2754                                     &rilVer, sizeof(rilVer));
2755
2756     // implicit radio state changed
2757     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
2758                                     NULL, 0);
2759
2760     // Send last NITZ time data, in case it was missed
2761     if (s_lastNITZTimeData != NULL) {
2762         sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize);
2763
2764         free(s_lastNITZTimeData);
2765         s_lastNITZTimeData = NULL;
2766     }
2767
2768     // Get version string
2769     if (s_callbacks.getVersion != NULL) {
2770         const char *version;
2771         version = s_callbacks.getVersion();
2772         RLOGI("RIL Daemon version: %s\n", version);
2773
2774         property_set(PROPERTY_RIL_IMPL, version);
2775     } else {
2776         RLOGI("RIL Daemon version: unavailable\n");
2777         property_set(PROPERTY_RIL_IMPL, "unavailable");
2778     }
2779
2780 }
2781
2782 static void listenCallback (int fd, short flags, void *param) {
2783     int ret;
2784     int err;
2785     int is_phone_socket;
2786     RecordStream *p_rs;
2787
2788     struct sockaddr_un peeraddr;
2789     socklen_t socklen = sizeof (peeraddr);
2790
2791     struct ucred creds;
2792     socklen_t szCreds = sizeof(creds);
2793
2794     struct passwd *pwd = NULL;
2795
2796     assert (s_fdCommand < 0);
2797     assert (fd == s_fdListen);
2798
2799     s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen);
2800
2801     if (s_fdCommand < 0 ) {
2802         RLOGE("Error on accept() errno:%d", errno);
2803         /* start listening for new connections again */
2804         rilEventAddWakeup(&s_listen_event);
2805               return;
2806     }
2807
2808     /* check the credential of the other side and only accept socket from
2809      * phone process
2810      */
2811     errno = 0;
2812     is_phone_socket = 0;
2813
2814     err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
2815
2816     if (err == 0 && szCreds > 0) {
2817         errno = 0;
2818         pwd = getpwuid(creds.uid);
2819         if (pwd != NULL) {
2820             if (strcmp(pwd->pw_name, PHONE_PROCESS) == 0) {
2821                 is_phone_socket = 1;
2822             } else {
2823                 RLOGE("RILD can't accept socket from process %s", pwd->pw_name);
2824             }
2825         } else {
2826             RLOGE("Error on getpwuid() errno: %d", errno);
2827         }
2828     } else {
2829         RLOGD("Error on getsockopt() errno: %d", errno);
2830     }
2831
2832     if ( !is_phone_socket ) {
2833       RLOGE("RILD must accept socket from %s", PHONE_PROCESS);
2834
2835       close(s_fdCommand);
2836       s_fdCommand = -1;
2837
2838       onCommandsSocketClosed();
2839
2840       /* start listening for new connections again */
2841       rilEventAddWakeup(&s_listen_event);
2842
2843       return;
2844     }
2845
2846     ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK);
2847
2848     if (ret < 0) {
2849         RLOGE ("Error setting O_NONBLOCK errno:%d", errno);
2850     }
2851
2852     RLOGI("libril: new connection");
2853
2854     p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES);
2855
2856     ril_event_set (&s_commands_event, s_fdCommand, 1,
2857         processCommandsCallback, p_rs);
2858
2859     rilEventAddWakeup (&s_commands_event);
2860
2861     onNewCommandConnect();
2862 }
2863
2864 static void freeDebugCallbackArgs(int number, char **args) {
2865     for (int i = 0; i < number; i++) {
2866         if (args[i] != NULL) {
2867             free(args[i]);
2868         }
2869     }
2870     free(args);
2871 }
2872
2873 static void debugCallback (int fd, short flags, void *param) {
2874     int acceptFD, option;
2875     struct sockaddr_un peeraddr;
2876     socklen_t socklen = sizeof (peeraddr);
2877     int data;
2878     unsigned int qxdm_data[6];
2879     const char *deactData[1] = {"1"};
2880     char *actData[1];
2881     RIL_Dial dialData;
2882     int hangupData[1] = {1};
2883     int number;
2884     char **args;
2885
2886     acceptFD = accept (fd,  (sockaddr *) &peeraddr, &socklen);
2887
2888     if (acceptFD < 0) {
2889         RLOGE ("error accepting on debug port: %d\n", errno);
2890         return;
2891     }
2892
2893     if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
2894         RLOGE ("error reading on socket: number of Args: \n");
2895         return;
2896     }
2897     args = (char **) malloc(sizeof(char*) * number);
2898
2899     for (int i = 0; i < number; i++) {
2900         int len;
2901         if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
2902             RLOGE ("error reading on socket: Len of Args: \n");
2903             freeDebugCallbackArgs(i, args);
2904             return;
2905         }
2906         // +1 for null-term
2907         args[i] = (char *) malloc((sizeof(char) * len) + 1);
2908         if (recv(acceptFD, args[i], sizeof(char) * len, 0)
2909             != (int)sizeof(char) * len) {
2910             RLOGE ("error reading on socket: Args[%d] \n", i);
2911             freeDebugCallbackArgs(i, args);
2912             return;
2913         }
2914         char * buf = args[i];
2915         buf[len] = 0;
2916     }
2917
2918     switch (atoi(args[0])) {
2919         case 0:
2920             RLOGI ("Connection on debug port: issuing reset.");
2921             issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0);
2922             break;
2923         case 1:
2924             RLOGI ("Connection on debug port: issuing radio power off.");
2925             data = 0;
2926             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2927             // Close the socket
2928             close(s_fdCommand);
2929             s_fdCommand = -1;
2930             break;
2931         case 2:
2932             RLOGI ("Debug port: issuing unsolicited voice network change.");
2933             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
2934                                       NULL, 0);
2935             break;
2936         case 3:
2937             RLOGI ("Debug port: QXDM log enable.");
2938             qxdm_data[0] = 65536;     // head.func_tag
2939             qxdm_data[1] = 16;        // head.len
2940             qxdm_data[2] = 1;         // mode: 1 for 'start logging'
2941             qxdm_data[3] = 32;        // log_file_size: 32megabytes
2942             qxdm_data[4] = 0;         // log_mask
2943             qxdm_data[5] = 8;         // log_max_fileindex
2944             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2945                               6 * sizeof(int));
2946             break;
2947         case 4:
2948             RLOGI ("Debug port: QXDM log disable.");
2949             qxdm_data[0] = 65536;
2950             qxdm_data[1] = 16;
2951             qxdm_data[2] = 0;          // mode: 0 for 'stop logging'
2952             qxdm_data[3] = 32;
2953             qxdm_data[4] = 0;
2954             qxdm_data[5] = 8;
2955             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2956                               6 * sizeof(int));
2957             break;
2958         case 5:
2959             RLOGI("Debug port: Radio On");
2960             data = 1;
2961             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2962             sleep(2);
2963             // Set network selection automatic.
2964             issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0);
2965             break;
2966         case 6:
2967             RLOGI("Debug port: Setup Data Call, Apn :%s\n", args[1]);
2968             actData[0] = args[1];
2969             issueLocalRequest(RIL_REQUEST_SETUP_DATA_CALL, &actData,
2970                               sizeof(actData));
2971             break;
2972         case 7:
2973             RLOGI("Debug port: Deactivate Data Call");
2974             issueLocalRequest(RIL_REQUEST_DEACTIVATE_DATA_CALL, &deactData,
2975                               sizeof(deactData));
2976             break;
2977         case 8:
2978             RLOGI("Debug port: Dial Call");
2979             dialData.clir = 0;
2980             dialData.address = args[1];
2981             issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData));
2982             break;
2983         case 9:
2984             RLOGI("Debug port: Answer Call");
2985             issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0);
2986             break;
2987         case 10:
2988             RLOGI("Debug port: End Call");
2989             issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
2990                               sizeof(hangupData));
2991             break;
2992         default:
2993             RLOGE ("Invalid request");
2994             break;
2995     }
2996     freeDebugCallbackArgs(number, args);
2997     close(acceptFD);
2998 }
2999
3000
3001 static void userTimerCallback (int fd, short flags, void *param) {
3002     UserCallbackInfo *p_info;
3003
3004     p_info = (UserCallbackInfo *)param;
3005
3006     p_info->p_callback(p_info->userParam);
3007
3008
3009     // FIXME generalize this...there should be a cancel mechanism
3010     if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
3011         s_last_wake_timeout_info = NULL;
3012     }
3013
3014     free(p_info);
3015 }
3016
3017
3018 static void *
3019 eventLoop(void *param) {
3020     int ret;
3021     int filedes[2];
3022
3023     ril_event_init();
3024
3025     pthread_mutex_lock(&s_startupMutex);
3026
3027     s_started = 1;
3028     pthread_cond_broadcast(&s_startupCond);
3029
3030     pthread_mutex_unlock(&s_startupMutex);
3031
3032     ret = pipe(filedes);
3033
3034     if (ret < 0) {
3035         RLOGE("Error in pipe() errno:%d", errno);
3036         return NULL;
3037     }
3038
3039     s_fdWakeupRead = filedes[0];
3040     s_fdWakeupWrite = filedes[1];
3041
3042     fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
3043
3044     ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
3045                 processWakeupCallback, NULL);
3046
3047     rilEventAddWakeup (&s_wakeupfd_event);
3048
3049     // Only returns on error
3050     ril_event_loop();
3051     RLOGE ("error in event_loop_base errno:%d", errno);
3052     // kill self to restart on error
3053     kill(0, SIGKILL);
3054
3055     return NULL;
3056 }
3057
3058 extern "C" void
3059 RIL_startEventLoop(void) {
3060     int ret;
3061     pthread_attr_t attr;
3062
3063     /* spin up eventLoop thread and wait for it to get started */
3064     s_started = 0;
3065     pthread_mutex_lock(&s_startupMutex);
3066
3067     pthread_attr_init (&attr);
3068     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3069     ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
3070
3071     while (s_started == 0) {
3072         pthread_cond_wait(&s_startupCond, &s_startupMutex);
3073     }
3074
3075     pthread_mutex_unlock(&s_startupMutex);
3076
3077     if (ret < 0) {
3078         RLOGE("Failed to create dispatch thread errno:%d", errno);
3079         return;
3080     }
3081 }
3082
3083 // Used for testing purpose only.
3084 extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
3085     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
3086 }
3087
3088 extern "C" void
3089 RIL_register (const RIL_RadioFunctions *callbacks) {
3090     int ret;
3091     int flags;
3092
3093     if (callbacks == NULL) {
3094         RLOGE("RIL_register: RIL_RadioFunctions * null");
3095         return;
3096     }
3097     if (callbacks->version < RIL_VERSION_MIN) {
3098         RLOGE("RIL_register: version %d is to old, min version is %d",
3099              callbacks->version, RIL_VERSION_MIN);
3100         return;
3101     }
3102     if (callbacks->version > RIL_VERSION) {
3103         RLOGE("RIL_register: version %d is too new, max version is %d",
3104              callbacks->version, RIL_VERSION);
3105         return;
3106     }
3107     RLOGE("RIL_register: RIL version %d", callbacks->version);
3108
3109     if (s_registerCalled > 0) {
3110         RLOGE("RIL_register has been called more than once. "
3111                 "Subsequent call ignored");
3112         return;
3113     }
3114
3115     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
3116
3117     s_registerCalled = 1;
3118
3119     // Little self-check
3120
3121     for (int i = 0; i < (int)NUM_ELEMS(s_commands); i++) {
3122         assert(i == s_commands[i].requestNumber);
3123     }
3124
3125     for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses); i++) {
3126         assert(i + RIL_UNSOL_RESPONSE_BASE
3127                 == s_unsolResponses[i].requestNumber);
3128     }
3129
3130     // New rild impl calls RIL_startEventLoop() first
3131     // old standalone impl wants it here.
3132
3133     if (s_started == 0) {
3134         RIL_startEventLoop();
3135     }
3136
3137     // start listen socket
3138
3139 #if 0
3140     ret = socket_local_server (SOCKET_NAME_RIL,
3141             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
3142
3143     if (ret < 0) {
3144         RLOGE("Unable to bind socket errno:%d", errno);
3145         exit (-1);
3146     }
3147     s_fdListen = ret;
3148
3149 #else
3150     s_fdListen = android_get_control_socket(SOCKET_NAME_RIL);
3151     if (s_fdListen < 0) {
3152         RLOGE("Failed to get socket '" SOCKET_NAME_RIL "'");
3153         exit(-1);
3154     }
3155
3156     ret = listen(s_fdListen, 4);
3157
3158     if (ret < 0) {
3159         RLOGE("Failed to listen on control socket '%d': %s",
3160              s_fdListen, strerror(errno));
3161         exit(-1);
3162     }
3163 #endif
3164
3165
3166     /* note: non-persistent so we can accept only one connection at a time */
3167     ril_event_set (&s_listen_event, s_fdListen, false,
3168                 listenCallback, NULL);
3169
3170     rilEventAddWakeup (&s_listen_event);
3171
3172 #if 1
3173     // start debug interface socket
3174
3175     s_fdDebug = android_get_control_socket(SOCKET_NAME_RIL_DEBUG);
3176     if (s_fdDebug < 0) {
3177         RLOGE("Failed to get socket '" SOCKET_NAME_RIL_DEBUG "' errno:%d", errno);
3178         exit(-1);
3179     }
3180
3181     ret = listen(s_fdDebug, 4);
3182
3183     if (ret < 0) {
3184         RLOGE("Failed to listen on ril debug socket '%d': %s",
3185              s_fdDebug, strerror(errno));
3186         exit(-1);
3187     }
3188
3189     ril_event_set (&s_debug_event, s_fdDebug, true,
3190                 debugCallback, NULL);
3191
3192     rilEventAddWakeup (&s_debug_event);
3193 #endif
3194
3195 }
3196
3197 static int
3198 checkAndDequeueRequestInfo(struct RequestInfo *pRI) {
3199     int ret = 0;
3200
3201     if (pRI == NULL) {
3202         return 0;
3203     }
3204
3205     pthread_mutex_lock(&s_pendingRequestsMutex);
3206
3207     for(RequestInfo **ppCur = &s_pendingRequests
3208         ; *ppCur != NULL
3209         ; ppCur = &((*ppCur)->p_next)
3210     ) {
3211         if (pRI == *ppCur) {
3212             ret = 1;
3213
3214             *ppCur = (*ppCur)->p_next;
3215             break;
3216         }
3217     }
3218
3219     pthread_mutex_unlock(&s_pendingRequestsMutex);
3220
3221     return ret;
3222 }
3223
3224
3225 extern "C" void
3226 RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen) {
3227     RequestInfo *pRI;
3228     int ret;
3229     size_t errorOffset;
3230
3231     pRI = (RequestInfo *)t;
3232
3233     if (!checkAndDequeueRequestInfo(pRI)) {
3234         RLOGE ("RIL_onRequestComplete: invalid RIL_Token");
3235         return;
3236     }
3237
3238     if (pRI->local > 0) {
3239         // Locally issued command...void only!
3240         // response does not go back up the command socket
3241         RLOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
3242
3243         goto done;
3244     }
3245
3246     appendPrintBuf("[%04d]< %s",
3247         pRI->token, requestToString(pRI->pCI->requestNumber));
3248
3249     if (pRI->cancelled == 0) {
3250         Parcel p;
3251
3252         p.writeInt32 (RESPONSE_SOLICITED);
3253         p.writeInt32 (pRI->token);
3254         errorOffset = p.dataPosition();
3255
3256         p.writeInt32 (e);
3257
3258         if (response != NULL) {
3259             // there is a response payload, no matter success or not.
3260             ret = pRI->pCI->responseFunction(p, response, responselen);
3261
3262             /* if an error occurred, rewind and mark it */
3263             if (ret != 0) {
3264                 p.setDataPosition(errorOffset);
3265                 p.writeInt32 (ret);
3266             }
3267         }
3268
3269         if (e != RIL_E_SUCCESS) {
3270             appendPrintBuf("%s fails by %s", printBuf, failCauseToString(e));
3271         }
3272
3273         if (s_fdCommand < 0) {
3274             RLOGD ("RIL onRequestComplete: Command channel closed");
3275         }
3276         sendResponse(p);
3277     }
3278
3279 done:
3280     free(pRI);
3281 }
3282
3283
3284 static void
3285 grabPartialWakeLock() {
3286     acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
3287 }
3288
3289 static void
3290 releaseWakeLock() {
3291     release_wake_lock(ANDROID_WAKE_LOCK_NAME);
3292 }
3293
3294 /**
3295  * Timer callback to put us back to sleep before the default timeout
3296  */
3297 static void
3298 wakeTimeoutCallback (void *param) {
3299     // We're using "param != NULL" as a cancellation mechanism
3300     if (param == NULL) {
3301         //RLOGD("wakeTimeout: releasing wake lock");
3302
3303         releaseWakeLock();
3304     } else {
3305         //RLOGD("wakeTimeout: releasing wake lock CANCELLED");
3306     }
3307 }
3308
3309 static int
3310 decodeVoiceRadioTechnology (RIL_RadioState radioState) {
3311     switch (radioState) {
3312         case RADIO_STATE_SIM_NOT_READY:
3313         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3314         case RADIO_STATE_SIM_READY:
3315             return RADIO_TECH_UMTS;
3316
3317         case RADIO_STATE_RUIM_NOT_READY:
3318         case RADIO_STATE_RUIM_READY:
3319         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3320         case RADIO_STATE_NV_NOT_READY:
3321         case RADIO_STATE_NV_READY:
3322             return RADIO_TECH_1xRTT;
3323
3324         default:
3325             RLOGD("decodeVoiceRadioTechnology: Invoked with incorrect RadioState");
3326             return -1;
3327     }
3328 }
3329
3330 static int
3331 decodeCdmaSubscriptionSource (RIL_RadioState radioState) {
3332     switch (radioState) {
3333         case RADIO_STATE_SIM_NOT_READY:
3334         case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3335         case RADIO_STATE_SIM_READY:
3336         case RADIO_STATE_RUIM_NOT_READY:
3337         case RADIO_STATE_RUIM_READY:
3338         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3339             return CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM;
3340
3341         case RADIO_STATE_NV_NOT_READY:
3342         case RADIO_STATE_NV_READY:
3343             return CDMA_SUBSCRIPTION_SOURCE_NV;
3344
3345         default:
3346             RLOGD("decodeCdmaSubscriptionSource: Invoked with incorrect RadioState");
3347             return -1;
3348     }
3349 }
3350
3351 static int
3352 decodeSimStatus (RIL_RadioState radioState) {
3353    switch (radioState) {
3354        case RADIO_STATE_SIM_NOT_READY:
3355        case RADIO_STATE_RUIM_NOT_READY:
3356        case RADIO_STATE_NV_NOT_READY:
3357        case RADIO_STATE_NV_READY:
3358            return -1;
3359        case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
3360        case RADIO_STATE_SIM_READY:
3361        case RADIO_STATE_RUIM_READY:
3362        case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
3363            return radioState;
3364        default:
3365            RLOGD("decodeSimStatus: Invoked with incorrect RadioState");
3366            return -1;
3367    }
3368 }
3369
3370 static bool is3gpp2(int radioTech) {
3371     switch (radioTech) {
3372         case RADIO_TECH_IS95A:
3373         case RADIO_TECH_IS95B:
3374         case RADIO_TECH_1xRTT:
3375         case RADIO_TECH_EVDO_0:
3376         case RADIO_TECH_EVDO_A:
3377         case RADIO_TECH_EVDO_B:
3378         case RADIO_TECH_EHRPD:
3379             return true;
3380         default:
3381             return false;
3382     }
3383 }
3384
3385 /* If RIL sends SIM states or RUIM states, store the voice radio
3386  * technology and subscription source information so that they can be
3387  * returned when telephony framework requests them
3388  */
3389 static RIL_RadioState
3390 processRadioState(RIL_RadioState newRadioState) {
3391
3392     if((newRadioState > RADIO_STATE_UNAVAILABLE) && (newRadioState < RADIO_STATE_ON)) {
3393         int newVoiceRadioTech;
3394         int newCdmaSubscriptionSource;
3395         int newSimStatus;
3396
3397         /* This is old RIL. Decode Subscription source and Voice Radio Technology
3398            from Radio State and send change notifications if there has been a change */
3399         newVoiceRadioTech = decodeVoiceRadioTechnology(newRadioState);
3400         if(newVoiceRadioTech != voiceRadioTech) {
3401             voiceRadioTech = newVoiceRadioTech;
3402             RIL_onUnsolicitedResponse (RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
3403                         &voiceRadioTech, sizeof(voiceRadioTech));
3404         }
3405         if(is3gpp2(newVoiceRadioTech)) {
3406             newCdmaSubscriptionSource = decodeCdmaSubscriptionSource(newRadioState);
3407             if(newCdmaSubscriptionSource != cdmaSubscriptionSource) {
3408                 cdmaSubscriptionSource = newCdmaSubscriptionSource;
3409                 RIL_onUnsolicitedResponse (RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
3410                         &cdmaSubscriptionSource, sizeof(cdmaSubscriptionSource));
3411             }
3412         }
3413         newSimStatus = decodeSimStatus(newRadioState);
3414         if(newSimStatus != simRuimStatus) {
3415             simRuimStatus = newSimStatus;
3416             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
3417         }
3418
3419         /* Send RADIO_ON to telephony */
3420         newRadioState = RADIO_STATE_ON;
3421     }
3422
3423     return newRadioState;
3424 }
3425
3426 extern "C"
3427 void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
3428                                 size_t datalen)
3429 {
3430     int unsolResponseIndex;
3431     int ret;
3432     int64_t timeReceived = 0;
3433     bool shouldScheduleTimeout = false;
3434     RIL_RadioState newState;
3435
3436     if (s_registerCalled == 0) {
3437         // Ignore RIL_onUnsolicitedResponse before RIL_register
3438         RLOGW("RIL_onUnsolicitedResponse called before RIL_register");
3439         return;
3440     }
3441
3442     unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
3443
3444     if ((unsolResponseIndex < 0)
3445         || (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
3446         RLOGE("unsupported unsolicited response code %d", unsolResponse);
3447         return;
3448     }
3449
3450     // Grab a wake lock if needed for this reponse,
3451     // as we exit we'll either release it immediately
3452     // or set a timer to release it later.
3453     switch (s_unsolResponses[unsolResponseIndex].wakeType) {
3454         case WAKE_PARTIAL:
3455             grabPartialWakeLock();
3456             shouldScheduleTimeout = true;
3457         break;
3458
3459         case DONT_WAKE:
3460         default:
3461             // No wake lock is grabed so don't set timeout
3462             shouldScheduleTimeout = false;
3463             break;
3464     }
3465
3466     // Mark the time this was received, doing this
3467     // after grabing the wakelock incase getting
3468     // the elapsedRealTime might cause us to goto
3469     // sleep.
3470     if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
3471         timeReceived = elapsedRealtime();
3472     }
3473
3474     appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
3475
3476     Parcel p;
3477
3478     p.writeInt32 (RESPONSE_UNSOLICITED);
3479     p.writeInt32 (unsolResponse);
3480
3481     ret = s_unsolResponses[unsolResponseIndex]
3482                 .responseFunction(p, data, datalen);
3483     if (ret != 0) {
3484         // Problem with the response. Don't continue;
3485         goto error_exit;
3486     }
3487
3488     // some things get more payload
3489     switch(unsolResponse) {
3490         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
3491             newState = processRadioState(s_callbacks.onStateRequest());
3492             p.writeInt32(newState);
3493             appendPrintBuf("%s {%s}", printBuf,
3494                 radioStateToString(s_callbacks.onStateRequest()));
3495         break;
3496
3497
3498         case RIL_UNSOL_NITZ_TIME_RECEIVED:
3499             // Store the time that this was received so the
3500             // handler of this message can account for
3501             // the time it takes to arrive and process. In
3502             // particular the system has been known to sleep
3503             // before this message can be processed.
3504             p.writeInt64(timeReceived);
3505         break;
3506     }
3507
3508     ret = sendResponse(p);
3509     if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
3510
3511         // Unfortunately, NITZ time is not poll/update like everything
3512         // else in the system. So, if the upstream client isn't connected,
3513         // keep a copy of the last NITZ response (with receive time noted
3514         // above) around so we can deliver it when it is connected
3515
3516         if (s_lastNITZTimeData != NULL) {
3517             free (s_lastNITZTimeData);
3518             s_lastNITZTimeData = NULL;
3519         }
3520
3521         s_lastNITZTimeData = malloc(p.dataSize());
3522         s_lastNITZTimeDataSize = p.dataSize();
3523         memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
3524     }
3525
3526     // For now, we automatically go back to sleep after TIMEVAL_WAKE_TIMEOUT
3527     // FIXME The java code should handshake here to release wake lock
3528
3529     if (shouldScheduleTimeout) {
3530         // Cancel the previous request
3531         if (s_last_wake_timeout_info != NULL) {
3532             s_last_wake_timeout_info->userParam = (void *)1;
3533         }
3534
3535         s_last_wake_timeout_info
3536             = internalRequestTimedCallback(wakeTimeoutCallback, NULL,
3537                                             &TIMEVAL_WAKE_TIMEOUT);
3538     }
3539
3540     // Normal exit
3541     return;
3542
3543 error_exit:
3544     if (shouldScheduleTimeout) {
3545         releaseWakeLock();
3546     }
3547 }
3548
3549 /** FIXME generalize this if you track UserCAllbackInfo, clear it
3550     when the callback occurs
3551 */
3552 static UserCallbackInfo *
3553 internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
3554                                 const struct timeval *relativeTime)
3555 {
3556     struct timeval myRelativeTime;
3557     UserCallbackInfo *p_info;
3558
3559     p_info = (UserCallbackInfo *) malloc (sizeof(UserCallbackInfo));
3560
3561     p_info->p_callback = callback;
3562     p_info->userParam = param;
3563
3564     if (relativeTime == NULL) {
3565         /* treat null parameter as a 0 relative time */
3566         memset (&myRelativeTime, 0, sizeof(myRelativeTime));
3567     } else {
3568         /* FIXME I think event_add's tv param is really const anyway */
3569         memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
3570     }
3571
3572     ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
3573
3574     ril_timer_add(&(p_info->event), &myRelativeTime);
3575
3576     triggerEvLoop();
3577     return p_info;
3578 }
3579
3580
3581 extern "C" void
3582 RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
3583                                 const struct timeval *relativeTime) {
3584     internalRequestTimedCallback (callback, param, relativeTime);
3585 }
3586
3587 const char *
3588 failCauseToString(RIL_Errno e) {
3589     switch(e) {
3590         case RIL_E_SUCCESS: return "E_SUCCESS";
3591         case RIL_E_RADIO_NOT_AVAILABLE: return "E_RADIO_NOT_AVAILABLE";
3592         case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
3593         case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
3594         case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
3595         case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
3596         case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
3597         case RIL_E_CANCELLED: return "E_CANCELLED";
3598         case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
3599         case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
3600         case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
3601         case RIL_E_SIM_ABSENT:return "E_SIM_ABSENT";
3602         case RIL_E_ILLEGAL_SIM_OR_ME:return "E_ILLEGAL_SIM_OR_ME";
3603 #ifdef FEATURE_MULTIMODE_ANDROID
3604         case RIL_E_SUBSCRIPTION_NOT_AVAILABLE:return "E_SUBSCRIPTION_NOT_AVAILABLE";
3605         case RIL_E_MODE_NOT_SUPPORTED:return "E_MODE_NOT_SUPPORTED";
3606 #endif
3607         default: return "<unknown error>";
3608     }
3609 }
3610
3611 const char *
3612 radioStateToString(RIL_RadioState s) {
3613     switch(s) {
3614         case RADIO_STATE_OFF: return "RADIO_OFF";
3615         case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
3616         case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
3617         case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
3618         case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
3619         case RADIO_STATE_RUIM_NOT_READY:return"RADIO_RUIM_NOT_READY";
3620         case RADIO_STATE_RUIM_READY:return"RADIO_RUIM_READY";
3621         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:return"RADIO_RUIM_LOCKED_OR_ABSENT";
3622         case RADIO_STATE_NV_NOT_READY:return"RADIO_NV_NOT_READY";
3623         case RADIO_STATE_NV_READY:return"RADIO_NV_READY";
3624         case RADIO_STATE_ON:return"RADIO_ON";
3625         default: return "<unknown state>";
3626     }
3627 }
3628
3629 const char *
3630 callStateToString(RIL_CallState s) {
3631     switch(s) {
3632         case RIL_CALL_ACTIVE : return "ACTIVE";
3633         case RIL_CALL_HOLDING: return "HOLDING";
3634         case RIL_CALL_DIALING: return "DIALING";
3635         case RIL_CALL_ALERTING: return "ALERTING";
3636         case RIL_CALL_INCOMING: return "INCOMING";
3637         case RIL_CALL_WAITING: return "WAITING";
3638         default: return "<unknown state>";
3639     }
3640 }
3641
3642 const char *
3643 requestToString(int request) {
3644 /*
3645  cat libs/telephony/ril_commands.h \
3646  | egrep "^ *{RIL_" \
3647  | sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
3648
3649
3650  cat libs/telephony/ril_unsol_commands.h \
3651  | egrep "^ *{RIL_" \
3652  | sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
3653
3654 */
3655     switch(request) {
3656         case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
3657         case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
3658         case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
3659         case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
3660         case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
3661         case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
3662         case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
3663         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
3664         case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
3665         case RIL_REQUEST_DIAL: return "DIAL";
3666         case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
3667         case RIL_REQUEST_HANGUP: return "HANGUP";
3668         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
3669         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
3670         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
3671         case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
3672         case RIL_REQUEST_UDUB: return "UDUB";
3673         case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
3674         case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
3675         case RIL_REQUEST_VOICE_REGISTRATION_STATE: return "VOICE_REGISTRATION_STATE";
3676         case RIL_REQUEST_DATA_REGISTRATION_STATE: return "DATA_REGISTRATION_STATE";
3677         case RIL_REQUEST_OPERATOR: return "OPERATOR";
3678         case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
3679         case RIL_REQUEST_DTMF: return "DTMF";
3680         case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
3681         case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
3682         case RIL_REQUEST_SETUP_DATA_CALL: return "SETUP_DATA_CALL";
3683         case RIL_REQUEST_SIM_IO: return "SIM_IO";
3684         case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
3685         case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
3686         case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
3687         case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
3688         case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
3689         case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
3690         case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
3691         case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
3692         case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
3693         case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
3694         case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
3695         case RIL_REQUEST_ANSWER: return "ANSWER";
3696         case RIL_REQUEST_DEACTIVATE_DATA_CALL: return "DEACTIVATE_DATA_CALL";
3697         case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
3698         case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
3699         case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
3700         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
3701         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
3702         case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
3703         case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
3704         case RIL_REQUEST_DTMF_START: return "DTMF_START";
3705         case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
3706         case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
3707         case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
3708         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
3709         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
3710         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
3711         case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
3712         case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
3713         case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
3714         case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: return "LAST_DATA_CALL_FAIL_CAUSE";
3715         case RIL_REQUEST_DATA_CALL_LIST: return "DATA_CALL_LIST";
3716         case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
3717         case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
3718         case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
3719         case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
3720         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
3721         case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
3722         case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
3723         case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
3724         case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
3725         case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
3726         case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
3727         case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
3728         case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
3729         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:return"CDMA_SET_SUBSCRIPTION_SOURCE";
3730         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:return"CDMA_SET_ROAMING_PREFERENCE";
3731         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:return"CDMA_QUERY_ROAMING_PREFERENCE";
3732         case RIL_REQUEST_SET_TTY_MODE:return"SET_TTY_MODE";
3733         case RIL_REQUEST_QUERY_TTY_MODE:return"QUERY_TTY_MODE";
3734         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE";
3735         case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE";
3736         case RIL_REQUEST_CDMA_FLASH:return"CDMA_FLASH";
3737         case RIL_REQUEST_CDMA_BURST_DTMF:return"CDMA_BURST_DTMF";
3738         case RIL_REQUEST_CDMA_SEND_SMS:return"CDMA_SEND_SMS";
3739         case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:return"CDMA_SMS_ACKNOWLEDGE";
3740         case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:return"GSM_GET_BROADCAST_SMS_CONFIG";
3741         case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:return"GSM_SET_BROADCAST_SMS_CONFIG";
3742         case RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG:return "CDMA_GET_BROADCAST_SMS_CONFIG";
3743         case RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG:return "CDMA_SET_BROADCAST_SMS_CONFIG";
3744         case RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION:return "CDMA_SMS_BROADCAST_ACTIVATION";
3745         case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: return"CDMA_VALIDATE_AND_WRITE_AKEY";
3746         case RIL_REQUEST_CDMA_SUBSCRIPTION: return"CDMA_SUBSCRIPTION";
3747         case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: return "CDMA_WRITE_SMS_TO_RUIM";
3748         case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: return "CDMA_DELETE_SMS_ON_RUIM";
3749         case RIL_REQUEST_DEVICE_IDENTITY: return "DEVICE_IDENTITY";
3750         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: return "EXIT_EMERGENCY_CALLBACK_MODE";
3751         case RIL_REQUEST_GET_SMSC_ADDRESS: return "GET_SMSC_ADDRESS";
3752         case RIL_REQUEST_SET_SMSC_ADDRESS: return "SET_SMSC_ADDRESS";
3753         case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: return "REPORT_SMS_MEMORY_STATUS";
3754         case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: return "REPORT_STK_SERVICE_IS_RUNNING";
3755         case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE: return "CDMA_GET_SUBSCRIPTION_SOURCE";
3756         case RIL_REQUEST_ISIM_AUTHENTICATION: return "ISIM_AUTHENTICATION";
3757         case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: return "RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU";
3758         case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: return "RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS";
3759         case RIL_REQUEST_VOICE_RADIO_TECH: return "VOICE_RADIO_TECH";
3760         case RIL_REQUEST_GET_CELL_INFO_LIST: return"GET_CELL_INFO_LIST";
3761         case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE: return"SET_UNSOL_CELL_INFO_LIST_RATE";
3762         case RIL_REQUEST_IMS_REGISTRATION_STATE: return "IMS_REGISTRATION_STATE";
3763         case RIL_REQUEST_IMS_SEND_SMS: return "IMS_SEND_SMS";
3764         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
3765         case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
3766         case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED";
3767         case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
3768         case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
3769         case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
3770         case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
3771         case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
3772         case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
3773         case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
3774         case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
3775         case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
3776         case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
3777         case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
3778         case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
3779         case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
3780         case RIL_UNSOL_DATA_CALL_LIST_CHANGED: return "UNSOL_DATA_CALL_LIST_CHANGED";
3781         case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
3782         case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED: return "UNSOL_RESPONSE_SIM_STATUS_CHANGED";
3783         case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS: return "UNSOL_NEW_CDMA_SMS";
3784         case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS: return "UNSOL_NEW_BROADCAST_SMS";
3785         case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL: return "UNSOL_CDMA_RUIM_SMS_STORAGE_FULL";
3786         case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "UNSOL_RESTRICTED_STATE_CHANGED";
3787         case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE: return "UNSOL_ENTER_EMERGENCY_CALLBACK_MODE";
3788         case RIL_UNSOL_CDMA_CALL_WAITING: return "UNSOL_CDMA_CALL_WAITING";
3789         case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS: return "UNSOL_CDMA_OTA_PROVISION_STATUS";
3790         case RIL_UNSOL_CDMA_INFO_REC: return "UNSOL_CDMA_INFO_REC";
3791         case RIL_UNSOL_OEM_HOOK_RAW: return "UNSOL_OEM_HOOK_RAW";
3792         case RIL_UNSOL_RINGBACK_TONE: return "UNSOL_RINGBACK_TONE";
3793         case RIL_UNSOL_RESEND_INCALL_MUTE: return "UNSOL_RESEND_INCALL_MUTE";
3794         case RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED: return "UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED";
3795         case RIL_UNSOL_CDMA_PRL_CHANGED: return "UNSOL_CDMA_PRL_CHANGED";
3796         case RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE: return "UNSOL_EXIT_EMERGENCY_CALLBACK_MODE";
3797         case RIL_UNSOL_RIL_CONNECTED: return "UNSOL_RIL_CONNECTED";
3798         case RIL_UNSOL_VOICE_RADIO_TECH_CHANGED: return "UNSOL_VOICE_RADIO_TECH_CHANGED";
3799         case RIL_UNSOL_CELL_INFO_LIST: return "UNSOL_CELL_INFO_LIST";
3800         case RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED: return "RESPONSE_IMS_NETWORK_STATE_CHANGED";
3801         default: return "<unknown request>";
3802     }
3803 }
3804
3805 } /* namespace android */