OSDN Git Service

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