OSDN Git Service

am c83d92e8: am 29d9e18b: Merge "Modifying description for RIL_UNSOL_RESPONSE_NEW_BRO...
[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       p.setDataPosition(pos);
1207       dispatchStrings(p, pRI);
1208     }
1209 }
1210
1211 static int
1212 blockingWrite(int fd, const void *buffer, size_t len) {
1213     size_t writeOffset = 0;
1214     const uint8_t *toWrite;
1215
1216     toWrite = (const uint8_t *)buffer;
1217
1218     while (writeOffset < len) {
1219         ssize_t written;
1220         do {
1221             written = write (fd, toWrite + writeOffset,
1222                                 len - writeOffset);
1223         } while (written < 0 && errno == EINTR);
1224
1225         if (written >= 0) {
1226             writeOffset += written;
1227         } else {   // written < 0
1228             LOGE ("RIL Response: unexpected error on write errno:%d", errno);
1229             close(fd);
1230             return -1;
1231         }
1232     }
1233
1234     return 0;
1235 }
1236
1237 static int
1238 sendResponseRaw (const void *data, size_t dataSize) {
1239     int fd = s_fdCommand;
1240     int ret;
1241     uint32_t header;
1242
1243     if (s_fdCommand < 0) {
1244         return -1;
1245     }
1246
1247     if (dataSize > MAX_COMMAND_BYTES) {
1248         LOGE("RIL: packet larger than %u (%u)",
1249                 MAX_COMMAND_BYTES, (unsigned int )dataSize);
1250
1251         return -1;
1252     }
1253
1254     pthread_mutex_lock(&s_writeMutex);
1255
1256     header = htonl(dataSize);
1257
1258     ret = blockingWrite(fd, (void *)&header, sizeof(header));
1259
1260     if (ret < 0) {
1261         pthread_mutex_unlock(&s_writeMutex);
1262         return ret;
1263     }
1264
1265     ret = blockingWrite(fd, data, dataSize);
1266
1267     if (ret < 0) {
1268         pthread_mutex_unlock(&s_writeMutex);
1269         return ret;
1270     }
1271
1272     pthread_mutex_unlock(&s_writeMutex);
1273
1274     return 0;
1275 }
1276
1277 static int
1278 sendResponse (Parcel &p) {
1279     printResponse;
1280     return sendResponseRaw(p.data(), p.dataSize());
1281 }
1282
1283 /** response is an int* pointing to an array of ints*/
1284
1285 static int
1286 responseInts(Parcel &p, void *response, size_t responselen) {
1287     int numInts;
1288
1289     if (response == NULL && responselen != 0) {
1290         LOGE("invalid response: NULL");
1291         return RIL_ERRNO_INVALID_RESPONSE;
1292     }
1293     if (responselen % sizeof(int) != 0) {
1294         LOGE("invalid response length %d expected multiple of %d\n",
1295             (int)responselen, (int)sizeof(int));
1296         return RIL_ERRNO_INVALID_RESPONSE;
1297     }
1298
1299     int *p_int = (int *) response;
1300
1301     numInts = responselen / sizeof(int *);
1302     p.writeInt32 (numInts);
1303
1304     /* each int*/
1305     startResponse;
1306     for (int i = 0 ; i < numInts ; i++) {
1307         appendPrintBuf("%s%d,", printBuf, p_int[i]);
1308         p.writeInt32(p_int[i]);
1309     }
1310     removeLastChar;
1311     closeResponse;
1312
1313     return 0;
1314 }
1315
1316 /** response is a char **, pointing to an array of char *'s */
1317 static int responseStrings(Parcel &p, void *response, size_t responselen) {
1318     int numStrings;
1319
1320     if (response == NULL && responselen != 0) {
1321         LOGE("invalid response: NULL");
1322         return RIL_ERRNO_INVALID_RESPONSE;
1323     }
1324     if (responselen % sizeof(char *) != 0) {
1325         LOGE("invalid response length %d expected multiple of %d\n",
1326             (int)responselen, (int)sizeof(char *));
1327         return RIL_ERRNO_INVALID_RESPONSE;
1328     }
1329
1330     if (response == NULL) {
1331         p.writeInt32 (0);
1332     } else {
1333         char **p_cur = (char **) response;
1334
1335         numStrings = responselen / sizeof(char *);
1336         p.writeInt32 (numStrings);
1337
1338         /* each string*/
1339         startResponse;
1340         for (int i = 0 ; i < numStrings ; i++) {
1341             appendPrintBuf("%s%s,", printBuf, (char*)p_cur[i]);
1342             writeStringToParcel (p, p_cur[i]);
1343         }
1344         removeLastChar;
1345         closeResponse;
1346     }
1347     return 0;
1348 }
1349
1350
1351 /**
1352  * NULL strings are accepted
1353  * FIXME currently ignores responselen
1354  */
1355 static int responseString(Parcel &p, void *response, size_t responselen) {
1356     /* one string only */
1357     startResponse;
1358     appendPrintBuf("%s%s", printBuf, (char*)response);
1359     closeResponse;
1360
1361     writeStringToParcel(p, (const char *)response);
1362
1363     return 0;
1364 }
1365
1366 static int responseVoid(Parcel &p, void *response, size_t responselen) {
1367     startResponse;
1368     removeLastChar;
1369     return 0;
1370 }
1371
1372 static int responseCallList(Parcel &p, void *response, size_t responselen) {
1373     int num;
1374
1375     if (response == NULL && responselen != 0) {
1376         LOGE("invalid response: NULL");
1377         return RIL_ERRNO_INVALID_RESPONSE;
1378     }
1379
1380     if (responselen % sizeof (RIL_Call *) != 0) {
1381         LOGE("invalid response length %d expected multiple of %d\n",
1382             (int)responselen, (int)sizeof (RIL_Call *));
1383         return RIL_ERRNO_INVALID_RESPONSE;
1384     }
1385
1386     startResponse;
1387     /* number of call info's */
1388     num = responselen / sizeof(RIL_Call *);
1389     p.writeInt32(num);
1390
1391     for (int i = 0 ; i < num ; i++) {
1392         RIL_Call *p_cur = ((RIL_Call **) response)[i];
1393         /* each call info */
1394         p.writeInt32(p_cur->state);
1395         p.writeInt32(p_cur->index);
1396         p.writeInt32(p_cur->toa);
1397         p.writeInt32(p_cur->isMpty);
1398         p.writeInt32(p_cur->isMT);
1399         p.writeInt32(p_cur->als);
1400         p.writeInt32(p_cur->isVoice);
1401         p.writeInt32(p_cur->isVoicePrivacy);
1402         writeStringToParcel(p, p_cur->number);
1403         p.writeInt32(p_cur->numberPresentation);
1404         writeStringToParcel(p, p_cur->name);
1405         p.writeInt32(p_cur->namePresentation);
1406         // Remove when partners upgrade to version 3
1407         if ((s_callbacks.version < 3) || (p_cur->uusInfo == NULL || p_cur->uusInfo->uusData == NULL)) {
1408             p.writeInt32(0); /* UUS Information is absent */
1409         } else {
1410             RIL_UUS_Info *uusInfo = p_cur->uusInfo;
1411             p.writeInt32(1); /* UUS Information is present */
1412             p.writeInt32(uusInfo->uusType);
1413             p.writeInt32(uusInfo->uusDcs);
1414             p.writeInt32(uusInfo->uusLength);
1415             p.write(uusInfo->uusData, uusInfo->uusLength);
1416         }
1417         appendPrintBuf("%s[id=%d,%s,toa=%d,",
1418             printBuf,
1419             p_cur->index,
1420             callStateToString(p_cur->state),
1421             p_cur->toa);
1422         appendPrintBuf("%s%s,%s,als=%d,%s,%s,",
1423             printBuf,
1424             (p_cur->isMpty)?"conf":"norm",
1425             (p_cur->isMT)?"mt":"mo",
1426             p_cur->als,
1427             (p_cur->isVoice)?"voc":"nonvoc",
1428             (p_cur->isVoicePrivacy)?"evp":"noevp");
1429         appendPrintBuf("%s%s,cli=%d,name='%s',%d]",
1430             printBuf,
1431             p_cur->number,
1432             p_cur->numberPresentation,
1433             p_cur->name,
1434             p_cur->namePresentation);
1435     }
1436     removeLastChar;
1437     closeResponse;
1438
1439     return 0;
1440 }
1441
1442 static int responseSMS(Parcel &p, void *response, size_t responselen) {
1443     if (response == NULL) {
1444         LOGE("invalid response: NULL");
1445         return RIL_ERRNO_INVALID_RESPONSE;
1446     }
1447
1448     if (responselen != sizeof (RIL_SMS_Response) ) {
1449         LOGE("invalid response length %d expected %d",
1450                 (int)responselen, (int)sizeof (RIL_SMS_Response));
1451         return RIL_ERRNO_INVALID_RESPONSE;
1452     }
1453
1454     RIL_SMS_Response *p_cur = (RIL_SMS_Response *) response;
1455
1456     p.writeInt32(p_cur->messageRef);
1457     writeStringToParcel(p, p_cur->ackPDU);
1458     p.writeInt32(p_cur->errorCode);
1459
1460     startResponse;
1461     appendPrintBuf("%s%d,%s,%d", printBuf, p_cur->messageRef,
1462         (char*)p_cur->ackPDU, p_cur->errorCode);
1463     closeResponse;
1464
1465     return 0;
1466 }
1467
1468 static int responseDataCallList(Parcel &p, void *response, size_t responselen)
1469 {
1470     if (response == NULL && responselen != 0) {
1471         LOGE("invalid response: NULL");
1472         return RIL_ERRNO_INVALID_RESPONSE;
1473     }
1474
1475     if (responselen % sizeof(RIL_Data_Call_Response) != 0) {
1476         LOGE("invalid response length %d expected multiple of %d",
1477                 (int)responselen, (int)sizeof(RIL_Data_Call_Response));
1478         return RIL_ERRNO_INVALID_RESPONSE;
1479     }
1480
1481     int num = responselen / sizeof(RIL_Data_Call_Response);
1482     p.writeInt32(num);
1483
1484     RIL_Data_Call_Response *p_cur = (RIL_Data_Call_Response *) response;
1485     startResponse;
1486     int i;
1487     for (i = 0; i < num; i++) {
1488         p.writeInt32(p_cur[i].cid);
1489         p.writeInt32(p_cur[i].active);
1490         writeStringToParcel(p, p_cur[i].type);
1491         writeStringToParcel(p, p_cur[i].apn);
1492         writeStringToParcel(p, p_cur[i].address);
1493         appendPrintBuf("%s[cid=%d,%s,%s,%s,%s],", printBuf,
1494             p_cur[i].cid,
1495             (p_cur[i].active==0)?"down":"up",
1496             (char*)p_cur[i].type,
1497             (char*)p_cur[i].apn,
1498             (char*)p_cur[i].address);
1499     }
1500     removeLastChar;
1501     closeResponse;
1502
1503     return 0;
1504 }
1505
1506 static int responseRaw(Parcel &p, void *response, size_t responselen) {
1507     if (response == NULL && responselen != 0) {
1508         LOGE("invalid response: NULL with responselen != 0");
1509         return RIL_ERRNO_INVALID_RESPONSE;
1510     }
1511
1512     // The java code reads -1 size as null byte array
1513     if (response == NULL) {
1514         p.writeInt32(-1);
1515     } else {
1516         p.writeInt32(responselen);
1517         p.write(response, responselen);
1518     }
1519
1520     return 0;
1521 }
1522
1523
1524 static int responseSIM_IO(Parcel &p, void *response, size_t responselen) {
1525     if (response == NULL) {
1526         LOGE("invalid response: NULL");
1527         return RIL_ERRNO_INVALID_RESPONSE;
1528     }
1529
1530     if (responselen != sizeof (RIL_SIM_IO_Response) ) {
1531         LOGE("invalid response length was %d expected %d",
1532                 (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
1533         return RIL_ERRNO_INVALID_RESPONSE;
1534     }
1535
1536     RIL_SIM_IO_Response *p_cur = (RIL_SIM_IO_Response *) response;
1537     p.writeInt32(p_cur->sw1);
1538     p.writeInt32(p_cur->sw2);
1539     writeStringToParcel(p, p_cur->simResponse);
1540
1541     startResponse;
1542     appendPrintBuf("%ssw1=0x%X,sw2=0x%X,%s", printBuf, p_cur->sw1, p_cur->sw2,
1543         (char*)p_cur->simResponse);
1544     closeResponse;
1545
1546
1547     return 0;
1548 }
1549
1550 static int responseCallForwards(Parcel &p, void *response, size_t responselen) {
1551     int num;
1552
1553     if (response == NULL && responselen != 0) {
1554         LOGE("invalid response: NULL");
1555         return RIL_ERRNO_INVALID_RESPONSE;
1556     }
1557
1558     if (responselen % sizeof(RIL_CallForwardInfo *) != 0) {
1559         LOGE("invalid response length %d expected multiple of %d",
1560                 (int)responselen, (int)sizeof(RIL_CallForwardInfo *));
1561         return RIL_ERRNO_INVALID_RESPONSE;
1562     }
1563
1564     /* number of call info's */
1565     num = responselen / sizeof(RIL_CallForwardInfo *);
1566     p.writeInt32(num);
1567
1568     startResponse;
1569     for (int i = 0 ; i < num ; i++) {
1570         RIL_CallForwardInfo *p_cur = ((RIL_CallForwardInfo **) response)[i];
1571
1572         p.writeInt32(p_cur->status);
1573         p.writeInt32(p_cur->reason);
1574         p.writeInt32(p_cur->serviceClass);
1575         p.writeInt32(p_cur->toa);
1576         writeStringToParcel(p, p_cur->number);
1577         p.writeInt32(p_cur->timeSeconds);
1578         appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
1579             (p_cur->status==1)?"enable":"disable",
1580             p_cur->reason, p_cur->serviceClass, p_cur->toa,
1581             (char*)p_cur->number,
1582             p_cur->timeSeconds);
1583     }
1584     removeLastChar;
1585     closeResponse;
1586
1587     return 0;
1588 }
1589
1590 static int responseSsn(Parcel &p, void *response, size_t responselen) {
1591     if (response == NULL) {
1592         LOGE("invalid response: NULL");
1593         return RIL_ERRNO_INVALID_RESPONSE;
1594     }
1595
1596     if (responselen != sizeof(RIL_SuppSvcNotification)) {
1597         LOGE("invalid response length was %d expected %d",
1598                 (int)responselen, (int)sizeof (RIL_SuppSvcNotification));
1599         return RIL_ERRNO_INVALID_RESPONSE;
1600     }
1601
1602     RIL_SuppSvcNotification *p_cur = (RIL_SuppSvcNotification *) response;
1603     p.writeInt32(p_cur->notificationType);
1604     p.writeInt32(p_cur->code);
1605     p.writeInt32(p_cur->index);
1606     p.writeInt32(p_cur->type);
1607     writeStringToParcel(p, p_cur->number);
1608
1609     startResponse;
1610     appendPrintBuf("%s%s,code=%d,id=%d,type=%d,%s", printBuf,
1611         (p_cur->notificationType==0)?"mo":"mt",
1612          p_cur->code, p_cur->index, p_cur->type,
1613         (char*)p_cur->number);
1614     closeResponse;
1615
1616     return 0;
1617 }
1618
1619 static int responseCellList(Parcel &p, void *response, size_t responselen) {
1620     int num;
1621
1622     if (response == NULL && responselen != 0) {
1623         LOGE("invalid response: NULL");
1624         return RIL_ERRNO_INVALID_RESPONSE;
1625     }
1626
1627     if (responselen % sizeof (RIL_NeighboringCell *) != 0) {
1628         LOGE("invalid response length %d expected multiple of %d\n",
1629             (int)responselen, (int)sizeof (RIL_NeighboringCell *));
1630         return RIL_ERRNO_INVALID_RESPONSE;
1631     }
1632
1633     startResponse;
1634     /* number of records */
1635     num = responselen / sizeof(RIL_NeighboringCell *);
1636     p.writeInt32(num);
1637
1638     for (int i = 0 ; i < num ; i++) {
1639         RIL_NeighboringCell *p_cur = ((RIL_NeighboringCell **) response)[i];
1640
1641         p.writeInt32(p_cur->rssi);
1642         writeStringToParcel (p, p_cur->cid);
1643
1644         appendPrintBuf("%s[cid=%s,rssi=%d],", printBuf,
1645             p_cur->cid, p_cur->rssi);
1646     }
1647     removeLastChar;
1648     closeResponse;
1649
1650     return 0;
1651 }
1652
1653 /**
1654  * Marshall the signalInfoRecord into the parcel if it exists.
1655  */
1656 static void marshallSignalInfoRecord(Parcel &p,
1657             RIL_CDMA_SignalInfoRecord &p_signalInfoRecord) {
1658     p.writeInt32(p_signalInfoRecord.isPresent);
1659     p.writeInt32(p_signalInfoRecord.signalType);
1660     p.writeInt32(p_signalInfoRecord.alertPitch);
1661     p.writeInt32(p_signalInfoRecord.signal);
1662 }
1663
1664 static int responseCdmaInformationRecords(Parcel &p,
1665             void *response, size_t responselen) {
1666     int num;
1667     char* string8 = NULL;
1668     int buffer_lenght;
1669     RIL_CDMA_InformationRecord *infoRec;
1670
1671     if (response == NULL && responselen != 0) {
1672         LOGE("invalid response: NULL");
1673         return RIL_ERRNO_INVALID_RESPONSE;
1674     }
1675
1676     if (responselen != sizeof (RIL_CDMA_InformationRecords)) {
1677         LOGE("invalid response length %d expected multiple of %d\n",
1678             (int)responselen, (int)sizeof (RIL_CDMA_InformationRecords *));
1679         return RIL_ERRNO_INVALID_RESPONSE;
1680     }
1681
1682     RIL_CDMA_InformationRecords *p_cur =
1683                              (RIL_CDMA_InformationRecords *) response;
1684     num = MIN(p_cur->numberOfInfoRecs, RIL_CDMA_MAX_NUMBER_OF_INFO_RECS);
1685
1686     startResponse;
1687     p.writeInt32(num);
1688
1689     for (int i = 0 ; i < num ; i++) {
1690         infoRec = &p_cur->infoRec[i];
1691         p.writeInt32(infoRec->name);
1692         switch (infoRec->name) {
1693             case RIL_CDMA_DISPLAY_INFO_REC:
1694             case RIL_CDMA_EXTENDED_DISPLAY_INFO_REC:
1695                 if (infoRec->rec.display.alpha_len >
1696                                          CDMA_ALPHA_INFO_BUFFER_LENGTH) {
1697                     LOGE("invalid display info response length %d \
1698                           expected not more than %d\n",
1699                          (int)infoRec->rec.display.alpha_len,
1700                          CDMA_ALPHA_INFO_BUFFER_LENGTH);
1701                     return RIL_ERRNO_INVALID_RESPONSE;
1702                 }
1703                 string8 = (char*) malloc((infoRec->rec.display.alpha_len + 1)
1704                                                              * sizeof(char) );
1705                 for (int i = 0 ; i < infoRec->rec.display.alpha_len ; i++) {
1706                     string8[i] = infoRec->rec.display.alpha_buf[i];
1707                 }
1708                 string8[infoRec->rec.display.alpha_len] = '\0';
1709                 writeStringToParcel(p, (const char*)string8);
1710                 free(string8);
1711                 string8 = NULL;
1712                 break;
1713             case RIL_CDMA_CALLED_PARTY_NUMBER_INFO_REC:
1714             case RIL_CDMA_CALLING_PARTY_NUMBER_INFO_REC:
1715             case RIL_CDMA_CONNECTED_NUMBER_INFO_REC:
1716                 if (infoRec->rec.number.len > CDMA_NUMBER_INFO_BUFFER_LENGTH) {
1717                     LOGE("invalid display info response length %d \
1718                           expected not more than %d\n",
1719                          (int)infoRec->rec.number.len,
1720                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
1721                     return RIL_ERRNO_INVALID_RESPONSE;
1722                 }
1723                 string8 = (char*) malloc((infoRec->rec.number.len + 1)
1724                                                              * sizeof(char) );
1725                 for (int i = 0 ; i < infoRec->rec.number.len; i++) {
1726                     string8[i] = infoRec->rec.number.buf[i];
1727                 }
1728                 string8[infoRec->rec.number.len] = '\0';
1729                 writeStringToParcel(p, (const char*)string8);
1730                 free(string8);
1731                 string8 = NULL;
1732                 p.writeInt32(infoRec->rec.number.number_type);
1733                 p.writeInt32(infoRec->rec.number.number_plan);
1734                 p.writeInt32(infoRec->rec.number.pi);
1735                 p.writeInt32(infoRec->rec.number.si);
1736                 break;
1737             case RIL_CDMA_SIGNAL_INFO_REC:
1738                 p.writeInt32(infoRec->rec.signal.isPresent);
1739                 p.writeInt32(infoRec->rec.signal.signalType);
1740                 p.writeInt32(infoRec->rec.signal.alertPitch);
1741                 p.writeInt32(infoRec->rec.signal.signal);
1742
1743                 appendPrintBuf("%sisPresent=%X, signalType=%X, \
1744                                 alertPitch=%X, signal=%X, ",
1745                    printBuf, (int)infoRec->rec.signal.isPresent,
1746                    (int)infoRec->rec.signal.signalType,
1747                    (int)infoRec->rec.signal.alertPitch,
1748                    (int)infoRec->rec.signal.signal);
1749                 removeLastChar;
1750                 break;
1751             case RIL_CDMA_REDIRECTING_NUMBER_INFO_REC:
1752                 if (infoRec->rec.redir.redirectingNumber.len >
1753                                               CDMA_NUMBER_INFO_BUFFER_LENGTH) {
1754                     LOGE("invalid display info response length %d \
1755                           expected not more than %d\n",
1756                          (int)infoRec->rec.redir.redirectingNumber.len,
1757                          CDMA_NUMBER_INFO_BUFFER_LENGTH);
1758                     return RIL_ERRNO_INVALID_RESPONSE;
1759                 }
1760                 string8 = (char*) malloc((infoRec->rec.redir.redirectingNumber
1761                                           .len + 1) * sizeof(char) );
1762                 for (int i = 0;
1763                          i < infoRec->rec.redir.redirectingNumber.len;
1764                          i++) {
1765                     string8[i] = infoRec->rec.redir.redirectingNumber.buf[i];
1766                 }
1767                 string8[infoRec->rec.redir.redirectingNumber.len] = '\0';
1768                 writeStringToParcel(p, (const char*)string8);
1769                 free(string8);
1770                 string8 = NULL;
1771                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_type);
1772                 p.writeInt32(infoRec->rec.redir.redirectingNumber.number_plan);
1773                 p.writeInt32(infoRec->rec.redir.redirectingNumber.pi);
1774                 p.writeInt32(infoRec->rec.redir.redirectingNumber.si);
1775                 p.writeInt32(infoRec->rec.redir.redirectingReason);
1776                 break;
1777             case RIL_CDMA_LINE_CONTROL_INFO_REC:
1778                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPolarityIncluded);
1779                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlToggle);
1780                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlReverse);
1781                 p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPowerDenial);
1782
1783                 appendPrintBuf("%slineCtrlPolarityIncluded=%d, \
1784                                 lineCtrlToggle=%d, lineCtrlReverse=%d, \
1785                                 lineCtrlPowerDenial=%d, ", printBuf,
1786                        (int)infoRec->rec.lineCtrl.lineCtrlPolarityIncluded,
1787                        (int)infoRec->rec.lineCtrl.lineCtrlToggle,
1788                        (int)infoRec->rec.lineCtrl.lineCtrlReverse,
1789                        (int)infoRec->rec.lineCtrl.lineCtrlPowerDenial);
1790                 removeLastChar;
1791                 break;
1792             case RIL_CDMA_T53_CLIR_INFO_REC:
1793                 p.writeInt32((int)(infoRec->rec.clir.cause));
1794
1795                 appendPrintBuf("%scause%d", printBuf, infoRec->rec.clir.cause);
1796                 removeLastChar;
1797                 break;
1798             case RIL_CDMA_T53_AUDIO_CONTROL_INFO_REC:
1799                 p.writeInt32(infoRec->rec.audioCtrl.upLink);
1800                 p.writeInt32(infoRec->rec.audioCtrl.downLink);
1801
1802                 appendPrintBuf("%supLink=%d, downLink=%d, ", printBuf,
1803                         infoRec->rec.audioCtrl.upLink,
1804                         infoRec->rec.audioCtrl.downLink);
1805                 removeLastChar;
1806                 break;
1807             case RIL_CDMA_T53_RELEASE_INFO_REC:
1808                 // TODO(Moto): See David Krause, he has the answer:)
1809                 LOGE("RIL_CDMA_T53_RELEASE_INFO_REC: return INVALID_RESPONSE");
1810                 return RIL_ERRNO_INVALID_RESPONSE;
1811             default:
1812                 LOGE("Incorrect name value");
1813                 return RIL_ERRNO_INVALID_RESPONSE;
1814         }
1815     }
1816     closeResponse;
1817
1818     return 0;
1819 }
1820
1821 static int responseRilSignalStrength(Parcel &p,
1822                     void *response, size_t responselen) {
1823     if (response == NULL && responselen != 0) {
1824         LOGE("invalid response: NULL");
1825         return RIL_ERRNO_INVALID_RESPONSE;
1826     }
1827
1828     if (responselen == sizeof (RIL_SignalStrength)) {
1829         // New RIL
1830         RIL_SignalStrength *p_cur = ((RIL_SignalStrength *) response);
1831
1832         p.writeInt32(p_cur->GW_SignalStrength.signalStrength);
1833         p.writeInt32(p_cur->GW_SignalStrength.bitErrorRate);
1834         p.writeInt32(p_cur->CDMA_SignalStrength.dbm);
1835         p.writeInt32(p_cur->CDMA_SignalStrength.ecio);
1836         p.writeInt32(p_cur->EVDO_SignalStrength.dbm);
1837         p.writeInt32(p_cur->EVDO_SignalStrength.ecio);
1838         p.writeInt32(p_cur->EVDO_SignalStrength.signalNoiseRatio);
1839
1840         startResponse;
1841         appendPrintBuf("%s[signalStrength=%d,bitErrorRate=%d,\
1842                 CDMA_SignalStrength.dbm=%d,CDMA_SignalStrength.ecio=%d,\
1843                 EVDO_SignalStrength.dbm =%d,EVDO_SignalStrength.ecio=%d,\
1844                 EVDO_SignalStrength.signalNoiseRatio=%d]",
1845                 printBuf,
1846                 p_cur->GW_SignalStrength.signalStrength,
1847                 p_cur->GW_SignalStrength.bitErrorRate,
1848                 p_cur->CDMA_SignalStrength.dbm,
1849                 p_cur->CDMA_SignalStrength.ecio,
1850                 p_cur->EVDO_SignalStrength.dbm,
1851                 p_cur->EVDO_SignalStrength.ecio,
1852                 p_cur->EVDO_SignalStrength.signalNoiseRatio);
1853
1854         closeResponse;
1855
1856     } else if (responselen % sizeof (int) == 0) {
1857         // Old RIL deprecated
1858         int *p_cur = (int *) response;
1859
1860         startResponse;
1861
1862         // With the Old RIL we see one or 2 integers.
1863         size_t num = responselen / sizeof (int); // Number of integers from ril
1864         size_t totalIntegers = 7; // Number of integers in RIL_SignalStrength
1865         size_t i;
1866
1867         appendPrintBuf("%s[", printBuf);
1868         for (i = 0; i < num; i++) {
1869             appendPrintBuf("%s %d", printBuf, *p_cur);
1870             p.writeInt32(*p_cur++);
1871         }
1872         appendPrintBuf("%s]", printBuf);
1873
1874         // Fill the remainder with zero's.
1875         for (; i < totalIntegers; i++) {
1876             p.writeInt32(0);
1877         }
1878
1879         closeResponse;
1880     } else {
1881         LOGE("invalid response length");
1882         return RIL_ERRNO_INVALID_RESPONSE;
1883     }
1884
1885     return 0;
1886 }
1887
1888 static int responseCallRing(Parcel &p, void *response, size_t responselen) {
1889     if ((response == NULL) || (responselen == 0)) {
1890         return responseVoid(p, response, responselen);
1891     } else {
1892         return responseCdmaSignalInfoRecord(p, response, responselen);
1893     }
1894 }
1895
1896 static int responseCdmaSignalInfoRecord(Parcel &p, void *response, size_t responselen) {
1897     if (response == NULL || responselen == 0) {
1898         LOGE("invalid response: NULL");
1899         return RIL_ERRNO_INVALID_RESPONSE;
1900     }
1901
1902     if (responselen != sizeof (RIL_CDMA_SignalInfoRecord)) {
1903         LOGE("invalid response length %d expected sizeof (RIL_CDMA_SignalInfoRecord) of %d\n",
1904             (int)responselen, (int)sizeof (RIL_CDMA_SignalInfoRecord));
1905         return RIL_ERRNO_INVALID_RESPONSE;
1906     }
1907
1908     startResponse;
1909
1910     RIL_CDMA_SignalInfoRecord *p_cur = ((RIL_CDMA_SignalInfoRecord *) response);
1911     marshallSignalInfoRecord(p, *p_cur);
1912
1913     appendPrintBuf("%s[isPresent=%d,signalType=%d,alertPitch=%d\
1914               signal=%d]",
1915               printBuf,
1916               p_cur->isPresent,
1917               p_cur->signalType,
1918               p_cur->alertPitch,
1919               p_cur->signal);
1920
1921     closeResponse;
1922     return 0;
1923 }
1924
1925 static int responseCdmaCallWaiting(Parcel &p, void *response,
1926             size_t responselen) {
1927     if (response == NULL && responselen != 0) {
1928         LOGE("invalid response: NULL");
1929         return RIL_ERRNO_INVALID_RESPONSE;
1930     }
1931
1932     if (responselen != sizeof(RIL_CDMA_CallWaiting)) {
1933         LOGE("invalid response length %d expected %d\n",
1934             (int)responselen, (int)sizeof(RIL_CDMA_CallWaiting));
1935         return RIL_ERRNO_INVALID_RESPONSE;
1936     }
1937
1938     startResponse;
1939     RIL_CDMA_CallWaiting *p_cur = ((RIL_CDMA_CallWaiting *) response);
1940
1941     writeStringToParcel (p, p_cur->number);
1942     p.writeInt32(p_cur->numberPresentation);
1943     writeStringToParcel (p, p_cur->name);
1944     marshallSignalInfoRecord(p, p_cur->signalInfoRecord);
1945
1946     appendPrintBuf("%snumber=%s,numberPresentation=%d, name=%s,\
1947             signalInfoRecord[isPresent=%d,signalType=%d,alertPitch=%d\
1948             signal=%d]",
1949             printBuf,
1950             p_cur->number,
1951             p_cur->numberPresentation,
1952             p_cur->name,
1953             p_cur->signalInfoRecord.isPresent,
1954             p_cur->signalInfoRecord.signalType,
1955             p_cur->signalInfoRecord.alertPitch,
1956             p_cur->signalInfoRecord.signal);
1957
1958     closeResponse;
1959
1960     return 0;
1961 }
1962
1963 static void triggerEvLoop() {
1964     int ret;
1965     if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
1966         /* trigger event loop to wakeup. No reason to do this,
1967          * if we're in the event loop thread */
1968          do {
1969             ret = write (s_fdWakeupWrite, " ", 1);
1970          } while (ret < 0 && errno == EINTR);
1971     }
1972 }
1973
1974 static void rilEventAddWakeup(struct ril_event *ev) {
1975     ril_event_add(ev);
1976     triggerEvLoop();
1977 }
1978
1979 static int responseSimStatus(Parcel &p, void *response, size_t responselen) {
1980     int i;
1981
1982     if (response == NULL && responselen != 0) {
1983         LOGE("invalid response: NULL");
1984         return RIL_ERRNO_INVALID_RESPONSE;
1985     }
1986
1987     if (responselen % sizeof (RIL_CardStatus *) != 0) {
1988         LOGE("invalid response length %d expected multiple of %d\n",
1989             (int)responselen, (int)sizeof (RIL_CardStatus *));
1990         return RIL_ERRNO_INVALID_RESPONSE;
1991     }
1992
1993     RIL_CardStatus *p_cur = ((RIL_CardStatus *) response);
1994
1995     p.writeInt32(p_cur->card_state);
1996     p.writeInt32(p_cur->universal_pin_state);
1997     p.writeInt32(p_cur->gsm_umts_subscription_app_index);
1998     p.writeInt32(p_cur->cdma_subscription_app_index);
1999     p.writeInt32(p_cur->num_applications);
2000
2001     startResponse;
2002     for (i = 0; i < p_cur->num_applications; i++) {
2003         p.writeInt32(p_cur->applications[i].app_type);
2004         p.writeInt32(p_cur->applications[i].app_state);
2005         p.writeInt32(p_cur->applications[i].perso_substate);
2006         writeStringToParcel(p, (const char*)(p_cur->applications[i].aid_ptr));
2007         writeStringToParcel(p, (const char*)
2008                                       (p_cur->applications[i].app_label_ptr));
2009         p.writeInt32(p_cur->applications[i].pin1_replaced);
2010         p.writeInt32(p_cur->applications[i].pin1);
2011         p.writeInt32(p_cur->applications[i].pin2);
2012         appendPrintBuf("%s[app_type=%d,app_state=%d,perso_substate=%d,\
2013                 aid_ptr=%s,app_label_ptr=%s,pin1_replaced=%d,pin1=%d,pin2=%d],",
2014                 printBuf,
2015                 p_cur->applications[i].app_type,
2016                 p_cur->applications[i].app_state,
2017                 p_cur->applications[i].perso_substate,
2018                 p_cur->applications[i].aid_ptr,
2019                 p_cur->applications[i].app_label_ptr,
2020                 p_cur->applications[i].pin1_replaced,
2021                 p_cur->applications[i].pin1,
2022                 p_cur->applications[i].pin2);
2023     }
2024     closeResponse;
2025
2026     return 0;
2027 }
2028
2029 static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2030     int num = responselen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
2031     p.writeInt32(num);
2032
2033     startResponse;
2034     RIL_GSM_BroadcastSmsConfigInfo **p_cur =
2035                 (RIL_GSM_BroadcastSmsConfigInfo **) response;
2036     for (int i = 0; i < num; i++) {
2037         p.writeInt32(p_cur[i]->fromServiceId);
2038         p.writeInt32(p_cur[i]->toServiceId);
2039         p.writeInt32(p_cur[i]->fromCodeScheme);
2040         p.writeInt32(p_cur[i]->toCodeScheme);
2041         p.writeInt32(p_cur[i]->selected);
2042
2043         appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId=%d, \
2044                 fromCodeScheme=%d, toCodeScheme=%d, selected =%d]",
2045                 printBuf, i, p_cur[i]->fromServiceId, p_cur[i]->toServiceId,
2046                 p_cur[i]->fromCodeScheme, p_cur[i]->toCodeScheme,
2047                 p_cur[i]->selected);
2048     }
2049     closeResponse;
2050
2051     return 0;
2052 }
2053
2054 static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen) {
2055     RIL_CDMA_BroadcastSmsConfigInfo **p_cur =
2056                (RIL_CDMA_BroadcastSmsConfigInfo **) response;
2057
2058     int num = responselen / sizeof (RIL_CDMA_BroadcastSmsConfigInfo *);
2059     p.writeInt32(num);
2060
2061     startResponse;
2062     for (int i = 0 ; i < num ; i++ ) {
2063         p.writeInt32(p_cur[i]->service_category);
2064         p.writeInt32(p_cur[i]->language);
2065         p.writeInt32(p_cur[i]->selected);
2066
2067         appendPrintBuf("%s [%d: srvice_category=%d, language =%d, \
2068               selected =%d], ",
2069               printBuf, i, p_cur[i]->service_category, p_cur[i]->language,
2070               p_cur[i]->selected);
2071     }
2072     closeResponse;
2073
2074     return 0;
2075 }
2076
2077 static int responseCdmaSms(Parcel &p, void *response, size_t responselen) {
2078     int num;
2079     int digitCount;
2080     int digitLimit;
2081     uint8_t uct;
2082     void* dest;
2083
2084     LOGD("Inside responseCdmaSms");
2085
2086     if (response == NULL && responselen != 0) {
2087         LOGE("invalid response: NULL");
2088         return RIL_ERRNO_INVALID_RESPONSE;
2089     }
2090
2091     if (responselen != sizeof(RIL_CDMA_SMS_Message)) {
2092         LOGE("invalid response length was %d expected %d",
2093                 (int)responselen, (int)sizeof(RIL_CDMA_SMS_Message));
2094         return RIL_ERRNO_INVALID_RESPONSE;
2095     }
2096
2097     RIL_CDMA_SMS_Message *p_cur = (RIL_CDMA_SMS_Message *) response;
2098     p.writeInt32(p_cur->uTeleserviceID);
2099     p.write(&(p_cur->bIsServicePresent),sizeof(uct));
2100     p.writeInt32(p_cur->uServicecategory);
2101     p.writeInt32(p_cur->sAddress.digit_mode);
2102     p.writeInt32(p_cur->sAddress.number_mode);
2103     p.writeInt32(p_cur->sAddress.number_type);
2104     p.writeInt32(p_cur->sAddress.number_plan);
2105     p.write(&(p_cur->sAddress.number_of_digits), sizeof(uct));
2106     digitLimit= MIN((p_cur->sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
2107     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2108         p.write(&(p_cur->sAddress.digits[digitCount]),sizeof(uct));
2109     }
2110
2111     p.writeInt32(p_cur->sSubAddress.subaddressType);
2112     p.write(&(p_cur->sSubAddress.odd),sizeof(uct));
2113     p.write(&(p_cur->sSubAddress.number_of_digits),sizeof(uct));
2114     digitLimit= MIN((p_cur->sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
2115     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2116         p.write(&(p_cur->sSubAddress.digits[digitCount]),sizeof(uct));
2117     }
2118
2119     digitLimit= MIN((p_cur->uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
2120     p.writeInt32(p_cur->uBearerDataLen);
2121     for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
2122        p.write(&(p_cur->aBearerData[digitCount]), sizeof(uct));
2123     }
2124
2125     startResponse;
2126     appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
2127             sAddress.digit_mode=%d, sAddress.number_mode=%d, sAddress.number_type=%d, ",
2128             printBuf, p_cur->uTeleserviceID,p_cur->bIsServicePresent,p_cur->uServicecategory,
2129             p_cur->sAddress.digit_mode, p_cur->sAddress.number_mode,p_cur->sAddress.number_type);
2130     closeResponse;
2131
2132     return 0;
2133 }
2134
2135 /**
2136  * A write on the wakeup fd is done just to pop us out of select()
2137  * We empty the buffer here and then ril_event will reset the timers on the
2138  * way back down
2139  */
2140 static void processWakeupCallback(int fd, short flags, void *param) {
2141     char buff[16];
2142     int ret;
2143
2144     LOGV("processWakeupCallback");
2145
2146     /* empty our wakeup socket out */
2147     do {
2148         ret = read(s_fdWakeupRead, &buff, sizeof(buff));
2149     } while (ret > 0 || (ret < 0 && errno == EINTR));
2150 }
2151
2152 static void onCommandsSocketClosed() {
2153     int ret;
2154     RequestInfo *p_cur;
2155
2156     /* mark pending requests as "cancelled" so we dont report responses */
2157
2158     ret = pthread_mutex_lock(&s_pendingRequestsMutex);
2159     assert (ret == 0);
2160
2161     p_cur = s_pendingRequests;
2162
2163     for (p_cur = s_pendingRequests
2164             ; p_cur != NULL
2165             ; p_cur  = p_cur->p_next
2166     ) {
2167         p_cur->cancelled = 1;
2168     }
2169
2170     ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
2171     assert (ret == 0);
2172 }
2173
2174 static void processCommandsCallback(int fd, short flags, void *param) {
2175     RecordStream *p_rs;
2176     void *p_record;
2177     size_t recordlen;
2178     int ret;
2179
2180     assert(fd == s_fdCommand);
2181
2182     p_rs = (RecordStream *)param;
2183
2184     for (;;) {
2185         /* loop until EAGAIN/EINTR, end of stream, or other error */
2186         ret = record_stream_get_next(p_rs, &p_record, &recordlen);
2187
2188         if (ret == 0 && p_record == NULL) {
2189             /* end-of-stream */
2190             break;
2191         } else if (ret < 0) {
2192             break;
2193         } else if (ret == 0) { /* && p_record != NULL */
2194             processCommandBuffer(p_record, recordlen);
2195         }
2196     }
2197
2198     if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
2199         /* fatal error or end-of-stream */
2200         if (ret != 0) {
2201             LOGE("error on reading command socket errno:%d\n", errno);
2202         } else {
2203             LOGW("EOS.  Closing command socket.");
2204         }
2205
2206         close(s_fdCommand);
2207         s_fdCommand = -1;
2208
2209         ril_event_del(&s_commands_event);
2210
2211         record_stream_free(p_rs);
2212
2213         /* start listening for new connections again */
2214         rilEventAddWakeup(&s_listen_event);
2215
2216         onCommandsSocketClosed();
2217     }
2218 }
2219
2220
2221 static void onNewCommandConnect() {
2222     // implicit radio state changed
2223     RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
2224                                     NULL, 0);
2225
2226     // Send last NITZ time data, in case it was missed
2227     if (s_lastNITZTimeData != NULL) {
2228         sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize);
2229
2230         free(s_lastNITZTimeData);
2231         s_lastNITZTimeData = NULL;
2232     }
2233
2234     // Get version string
2235     if (s_callbacks.getVersion != NULL) {
2236         const char *version;
2237         version = s_callbacks.getVersion();
2238         LOGI("RIL Daemon version: %s\n", version);
2239
2240         property_set(PROPERTY_RIL_IMPL, version);
2241     } else {
2242         LOGI("RIL Daemon version: unavailable\n");
2243         property_set(PROPERTY_RIL_IMPL, "unavailable");
2244     }
2245
2246 }
2247
2248 static void listenCallback (int fd, short flags, void *param) {
2249     int ret;
2250     int err;
2251     int is_phone_socket;
2252     RecordStream *p_rs;
2253
2254     struct sockaddr_un peeraddr;
2255     socklen_t socklen = sizeof (peeraddr);
2256
2257     struct ucred creds;
2258     socklen_t szCreds = sizeof(creds);
2259
2260     struct passwd *pwd = NULL;
2261
2262     assert (s_fdCommand < 0);
2263     assert (fd == s_fdListen);
2264
2265     s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen);
2266
2267     if (s_fdCommand < 0 ) {
2268         LOGE("Error on accept() errno:%d", errno);
2269         /* start listening for new connections again */
2270         rilEventAddWakeup(&s_listen_event);
2271               return;
2272     }
2273
2274     /* check the credential of the other side and only accept socket from
2275      * phone process
2276      */
2277     errno = 0;
2278     is_phone_socket = 0;
2279
2280     err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
2281
2282     if (err == 0 && szCreds > 0) {
2283         errno = 0;
2284         pwd = getpwuid(creds.uid);
2285         if (pwd != NULL) {
2286             if (strcmp(pwd->pw_name, PHONE_PROCESS) == 0) {
2287                 is_phone_socket = 1;
2288             } else {
2289                 LOGE("RILD can't accept socket from process %s", pwd->pw_name);
2290             }
2291         } else {
2292             LOGE("Error on getpwuid() errno: %d", errno);
2293         }
2294     } else {
2295         LOGD("Error on getsockopt() errno: %d", errno);
2296     }
2297
2298     if ( !is_phone_socket ) {
2299       LOGE("RILD must accept socket from %s", PHONE_PROCESS);
2300
2301       close(s_fdCommand);
2302       s_fdCommand = -1;
2303
2304       onCommandsSocketClosed();
2305
2306       /* start listening for new connections again */
2307       rilEventAddWakeup(&s_listen_event);
2308
2309       return;
2310     }
2311
2312     ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK);
2313
2314     if (ret < 0) {
2315         LOGE ("Error setting O_NONBLOCK errno:%d", errno);
2316     }
2317
2318     LOGI("libril: new connection");
2319
2320     p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES);
2321
2322     ril_event_set (&s_commands_event, s_fdCommand, 1,
2323         processCommandsCallback, p_rs);
2324
2325     rilEventAddWakeup (&s_commands_event);
2326
2327     onNewCommandConnect();
2328 }
2329
2330 static void freeDebugCallbackArgs(int number, char **args) {
2331     for (int i = 0; i < number; i++) {
2332         if (args[i] != NULL) {
2333             free(args[i]);
2334         }
2335     }
2336     free(args);
2337 }
2338
2339 static void debugCallback (int fd, short flags, void *param) {
2340     int acceptFD, option;
2341     struct sockaddr_un peeraddr;
2342     socklen_t socklen = sizeof (peeraddr);
2343     int data;
2344     unsigned int qxdm_data[6];
2345     const char *deactData[1] = {"1"};
2346     char *actData[1];
2347     RIL_Dial dialData;
2348     int hangupData[1] = {1};
2349     int number;
2350     char **args;
2351
2352     acceptFD = accept (fd,  (sockaddr *) &peeraddr, &socklen);
2353
2354     if (acceptFD < 0) {
2355         LOGE ("error accepting on debug port: %d\n", errno);
2356         return;
2357     }
2358
2359     if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
2360         LOGE ("error reading on socket: number of Args: \n");
2361         return;
2362     }
2363     args = (char **) malloc(sizeof(char*) * number);
2364
2365     for (int i = 0; i < number; i++) {
2366         int len;
2367         if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
2368             LOGE ("error reading on socket: Len of Args: \n");
2369             freeDebugCallbackArgs(i, args);
2370             return;
2371         }
2372         // +1 for null-term
2373         args[i] = (char *) malloc((sizeof(char) * len) + 1);
2374         if (recv(acceptFD, args[i], sizeof(char) * len, 0)
2375             != (int)sizeof(char) * len) {
2376             LOGE ("error reading on socket: Args[%d] \n", i);
2377             freeDebugCallbackArgs(i, args);
2378             return;
2379         }
2380         char * buf = args[i];
2381         buf[len] = 0;
2382     }
2383
2384     switch (atoi(args[0])) {
2385         case 0:
2386             LOGI ("Connection on debug port: issuing reset.");
2387             issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0);
2388             break;
2389         case 1:
2390             LOGI ("Connection on debug port: issuing radio power off.");
2391             data = 0;
2392             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2393             // Close the socket
2394             close(s_fdCommand);
2395             s_fdCommand = -1;
2396             break;
2397         case 2:
2398             LOGI ("Debug port: issuing unsolicited network change.");
2399             RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_NETWORK_STATE_CHANGED,
2400                                       NULL, 0);
2401             break;
2402         case 3:
2403             LOGI ("Debug port: QXDM log enable.");
2404             qxdm_data[0] = 65536;     // head.func_tag
2405             qxdm_data[1] = 16;        // head.len
2406             qxdm_data[2] = 1;         // mode: 1 for 'start logging'
2407             qxdm_data[3] = 32;        // log_file_size: 32megabytes
2408             qxdm_data[4] = 0;         // log_mask
2409             qxdm_data[5] = 8;         // log_max_fileindex
2410             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2411                               6 * sizeof(int));
2412             break;
2413         case 4:
2414             LOGI ("Debug port: QXDM log disable.");
2415             qxdm_data[0] = 65536;
2416             qxdm_data[1] = 16;
2417             qxdm_data[2] = 0;          // mode: 0 for 'stop logging'
2418             qxdm_data[3] = 32;
2419             qxdm_data[4] = 0;
2420             qxdm_data[5] = 8;
2421             issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
2422                               6 * sizeof(int));
2423             break;
2424         case 5:
2425             LOGI("Debug port: Radio On");
2426             data = 1;
2427             issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
2428             sleep(2);
2429             // Set network selection automatic.
2430             issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0);
2431             break;
2432         case 6:
2433             LOGI("Debug port: Setup Data Call, Apn :%s\n", args[1]);
2434             actData[0] = args[1];
2435             issueLocalRequest(RIL_REQUEST_SETUP_DATA_CALL, &actData,
2436                               sizeof(actData));
2437             break;
2438         case 7:
2439             LOGI("Debug port: Deactivate Data Call");
2440             issueLocalRequest(RIL_REQUEST_DEACTIVATE_DATA_CALL, &deactData,
2441                               sizeof(deactData));
2442             break;
2443         case 8:
2444             LOGI("Debug port: Dial Call");
2445             dialData.clir = 0;
2446             dialData.address = args[1];
2447             issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData));
2448             break;
2449         case 9:
2450             LOGI("Debug port: Answer Call");
2451             issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0);
2452             break;
2453         case 10:
2454             LOGI("Debug port: End Call");
2455             issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
2456                               sizeof(hangupData));
2457             break;
2458         default:
2459             LOGE ("Invalid request");
2460             break;
2461     }
2462     freeDebugCallbackArgs(number, args);
2463     close(acceptFD);
2464 }
2465
2466
2467 static void userTimerCallback (int fd, short flags, void *param) {
2468     UserCallbackInfo *p_info;
2469
2470     p_info = (UserCallbackInfo *)param;
2471
2472     p_info->p_callback(p_info->userParam);
2473
2474
2475     // FIXME generalize this...there should be a cancel mechanism
2476     if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
2477         s_last_wake_timeout_info = NULL;
2478     }
2479
2480     free(p_info);
2481 }
2482
2483
2484 static void *
2485 eventLoop(void *param) {
2486     int ret;
2487     int filedes[2];
2488
2489     ril_event_init();
2490
2491     pthread_mutex_lock(&s_startupMutex);
2492
2493     s_started = 1;
2494     pthread_cond_broadcast(&s_startupCond);
2495
2496     pthread_mutex_unlock(&s_startupMutex);
2497
2498     ret = pipe(filedes);
2499
2500     if (ret < 0) {
2501         LOGE("Error in pipe() errno:%d", errno);
2502         return NULL;
2503     }
2504
2505     s_fdWakeupRead = filedes[0];
2506     s_fdWakeupWrite = filedes[1];
2507
2508     fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
2509
2510     ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
2511                 processWakeupCallback, NULL);
2512
2513     rilEventAddWakeup (&s_wakeupfd_event);
2514
2515     // Only returns on error
2516     ril_event_loop();
2517     LOGE ("error in event_loop_base errno:%d", errno);
2518
2519     return NULL;
2520 }
2521
2522 extern "C" void
2523 RIL_startEventLoop(void) {
2524     int ret;
2525     pthread_attr_t attr;
2526
2527     /* spin up eventLoop thread and wait for it to get started */
2528     s_started = 0;
2529     pthread_mutex_lock(&s_startupMutex);
2530
2531     pthread_attr_init (&attr);
2532     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2533     ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
2534
2535     while (s_started == 0) {
2536         pthread_cond_wait(&s_startupCond, &s_startupMutex);
2537     }
2538
2539     pthread_mutex_unlock(&s_startupMutex);
2540
2541     if (ret < 0) {
2542         LOGE("Failed to create dispatch thread errno:%d", errno);
2543         return;
2544     }
2545 }
2546
2547 // Used for testing purpose only.
2548 extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
2549     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
2550 }
2551
2552 extern "C" void
2553 RIL_register (const RIL_RadioFunctions *callbacks) {
2554     int ret;
2555     int flags;
2556
2557     if (callbacks == NULL || ((callbacks->version != RIL_VERSION)
2558                 && (callbacks->version < 2))) { // Remove when partners upgrade to version 3
2559         LOGE(
2560             "RIL_register: RIL_RadioFunctions * null or invalid version"
2561             " (expected %d)", RIL_VERSION);
2562         return;
2563     }
2564     if (callbacks->version < RIL_VERSION) {
2565         LOGE ("RIL_register: upgrade RIL to version %d current version=%d",
2566               RIL_VERSION, callbacks->version);
2567     }
2568
2569     if (s_registerCalled > 0) {
2570         LOGE("RIL_register has been called more than once. "
2571                 "Subsequent call ignored");
2572         return;
2573     }
2574
2575     memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
2576
2577     s_registerCalled = 1;
2578
2579     // Little self-check
2580
2581     for (int i = 0; i < (int)NUM_ELEMS(s_commands); i++) {
2582         assert(i == s_commands[i].requestNumber);
2583     }
2584
2585     for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses); i++) {
2586         assert(i + RIL_UNSOL_RESPONSE_BASE
2587                 == s_unsolResponses[i].requestNumber);
2588     }
2589
2590     // New rild impl calls RIL_startEventLoop() first
2591     // old standalone impl wants it here.
2592
2593     if (s_started == 0) {
2594         RIL_startEventLoop();
2595     }
2596
2597     // start listen socket
2598
2599 #if 0
2600     ret = socket_local_server (SOCKET_NAME_RIL,
2601             ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
2602
2603     if (ret < 0) {
2604         LOGE("Unable to bind socket errno:%d", errno);
2605         exit (-1);
2606     }
2607     s_fdListen = ret;
2608
2609 #else
2610     s_fdListen = android_get_control_socket(SOCKET_NAME_RIL);
2611     if (s_fdListen < 0) {
2612         LOGE("Failed to get socket '" SOCKET_NAME_RIL "'");
2613         exit(-1);
2614     }
2615
2616     ret = listen(s_fdListen, 4);
2617
2618     if (ret < 0) {
2619         LOGE("Failed to listen on control socket '%d': %s",
2620              s_fdListen, strerror(errno));
2621         exit(-1);
2622     }
2623 #endif
2624
2625
2626     /* note: non-persistent so we can accept only one connection at a time */
2627     ril_event_set (&s_listen_event, s_fdListen, false,
2628                 listenCallback, NULL);
2629
2630     rilEventAddWakeup (&s_listen_event);
2631
2632 #if 1
2633     // start debug interface socket
2634
2635     s_fdDebug = android_get_control_socket(SOCKET_NAME_RIL_DEBUG);
2636     if (s_fdDebug < 0) {
2637         LOGE("Failed to get socket '" SOCKET_NAME_RIL_DEBUG "' errno:%d", errno);
2638         exit(-1);
2639     }
2640
2641     ret = listen(s_fdDebug, 4);
2642
2643     if (ret < 0) {
2644         LOGE("Failed to listen on ril debug socket '%d': %s",
2645              s_fdDebug, strerror(errno));
2646         exit(-1);
2647     }
2648
2649     ril_event_set (&s_debug_event, s_fdDebug, true,
2650                 debugCallback, NULL);
2651
2652     rilEventAddWakeup (&s_debug_event);
2653 #endif
2654
2655 }
2656
2657 static int
2658 checkAndDequeueRequestInfo(struct RequestInfo *pRI) {
2659     int ret = 0;
2660
2661     if (pRI == NULL) {
2662         return 0;
2663     }
2664
2665     pthread_mutex_lock(&s_pendingRequestsMutex);
2666
2667     for(RequestInfo **ppCur = &s_pendingRequests
2668         ; *ppCur != NULL
2669         ; ppCur = &((*ppCur)->p_next)
2670     ) {
2671         if (pRI == *ppCur) {
2672             ret = 1;
2673
2674             *ppCur = (*ppCur)->p_next;
2675             break;
2676         }
2677     }
2678
2679     pthread_mutex_unlock(&s_pendingRequestsMutex);
2680
2681     return ret;
2682 }
2683
2684
2685 extern "C" void
2686 RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen) {
2687     RequestInfo *pRI;
2688     int ret;
2689     size_t errorOffset;
2690
2691     pRI = (RequestInfo *)t;
2692
2693     if (!checkAndDequeueRequestInfo(pRI)) {
2694         LOGE ("RIL_onRequestComplete: invalid RIL_Token");
2695         return;
2696     }
2697
2698     if (pRI->local > 0) {
2699         // Locally issued command...void only!
2700         // response does not go back up the command socket
2701         LOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
2702
2703         goto done;
2704     }
2705
2706     appendPrintBuf("[%04d]< %s",
2707         pRI->token, requestToString(pRI->pCI->requestNumber));
2708
2709     if (pRI->cancelled == 0) {
2710         Parcel p;
2711
2712         p.writeInt32 (RESPONSE_SOLICITED);
2713         p.writeInt32 (pRI->token);
2714         errorOffset = p.dataPosition();
2715
2716         p.writeInt32 (e);
2717
2718         if (response != NULL) {
2719             // there is a response payload, no matter success or not.
2720             ret = pRI->pCI->responseFunction(p, response, responselen);
2721
2722             /* if an error occurred, rewind and mark it */
2723             if (ret != 0) {
2724                 p.setDataPosition(errorOffset);
2725                 p.writeInt32 (ret);
2726             }
2727         }
2728
2729         if (e != RIL_E_SUCCESS) {
2730             appendPrintBuf("%s fails by %s", printBuf, failCauseToString(e));
2731         }
2732
2733         if (s_fdCommand < 0) {
2734             LOGD ("RIL onRequestComplete: Command channel closed");
2735         }
2736         sendResponse(p);
2737     }
2738
2739 done:
2740     free(pRI);
2741 }
2742
2743
2744 static void
2745 grabPartialWakeLock() {
2746     acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
2747 }
2748
2749 static void
2750 releaseWakeLock() {
2751     release_wake_lock(ANDROID_WAKE_LOCK_NAME);
2752 }
2753
2754 /**
2755  * Timer callback to put us back to sleep before the default timeout
2756  */
2757 static void
2758 wakeTimeoutCallback (void *param) {
2759     // We're using "param != NULL" as a cancellation mechanism
2760     if (param == NULL) {
2761         //LOGD("wakeTimeout: releasing wake lock");
2762
2763         releaseWakeLock();
2764     } else {
2765         //LOGD("wakeTimeout: releasing wake lock CANCELLED");
2766     }
2767 }
2768
2769 extern "C"
2770 void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
2771                                 size_t datalen)
2772 {
2773     int unsolResponseIndex;
2774     int ret;
2775     int64_t timeReceived = 0;
2776     bool shouldScheduleTimeout = false;
2777
2778     if (s_registerCalled == 0) {
2779         // Ignore RIL_onUnsolicitedResponse before RIL_register
2780         LOGW("RIL_onUnsolicitedResponse called before RIL_register");
2781         return;
2782     }
2783
2784     unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
2785
2786     if ((unsolResponseIndex < 0)
2787         || (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
2788         LOGE("unsupported unsolicited response code %d", unsolResponse);
2789         return;
2790     }
2791
2792     // Grab a wake lock if needed for this reponse,
2793     // as we exit we'll either release it immediately
2794     // or set a timer to release it later.
2795     switch (s_unsolResponses[unsolResponseIndex].wakeType) {
2796         case WAKE_PARTIAL:
2797             grabPartialWakeLock();
2798             shouldScheduleTimeout = true;
2799         break;
2800
2801         case DONT_WAKE:
2802         default:
2803             // No wake lock is grabed so don't set timeout
2804             shouldScheduleTimeout = false;
2805             break;
2806     }
2807
2808     // Mark the time this was received, doing this
2809     // after grabing the wakelock incase getting
2810     // the elapsedRealTime might cause us to goto
2811     // sleep.
2812     if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
2813         timeReceived = elapsedRealtime();
2814     }
2815
2816     appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
2817
2818     Parcel p;
2819
2820     p.writeInt32 (RESPONSE_UNSOLICITED);
2821     p.writeInt32 (unsolResponse);
2822
2823     ret = s_unsolResponses[unsolResponseIndex]
2824                 .responseFunction(p, data, datalen);
2825     if (ret != 0) {
2826         // Problem with the response. Don't continue;
2827         goto error_exit;
2828     }
2829
2830     // some things get more payload
2831     switch(unsolResponse) {
2832         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
2833             p.writeInt32(s_callbacks.onStateRequest());
2834             appendPrintBuf("%s {%s}", printBuf,
2835                 radioStateToString(s_callbacks.onStateRequest()));
2836         break;
2837
2838
2839         case RIL_UNSOL_NITZ_TIME_RECEIVED:
2840             // Store the time that this was received so the
2841             // handler of this message can account for
2842             // the time it takes to arrive and process. In
2843             // particular the system has been known to sleep
2844             // before this message can be processed.
2845             p.writeInt64(timeReceived);
2846         break;
2847     }
2848
2849     ret = sendResponse(p);
2850     if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
2851
2852         // Unfortunately, NITZ time is not poll/update like everything
2853         // else in the system. So, if the upstream client isn't connected,
2854         // keep a copy of the last NITZ response (with receive time noted
2855         // above) around so we can deliver it when it is connected
2856
2857         if (s_lastNITZTimeData != NULL) {
2858             free (s_lastNITZTimeData);
2859             s_lastNITZTimeData = NULL;
2860         }
2861
2862         s_lastNITZTimeData = malloc(p.dataSize());
2863         s_lastNITZTimeDataSize = p.dataSize();
2864         memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
2865     }
2866
2867     // For now, we automatically go back to sleep after TIMEVAL_WAKE_TIMEOUT
2868     // FIXME The java code should handshake here to release wake lock
2869
2870     if (shouldScheduleTimeout) {
2871         // Cancel the previous request
2872         if (s_last_wake_timeout_info != NULL) {
2873             s_last_wake_timeout_info->userParam = (void *)1;
2874         }
2875
2876         s_last_wake_timeout_info
2877             = internalRequestTimedCallback(wakeTimeoutCallback, NULL,
2878                                             &TIMEVAL_WAKE_TIMEOUT);
2879     }
2880
2881     // Normal exit
2882     return;
2883
2884 error_exit:
2885     if (shouldScheduleTimeout) {
2886         releaseWakeLock();
2887     }
2888 }
2889
2890 /** FIXME generalize this if you track UserCAllbackInfo, clear it
2891     when the callback occurs
2892 */
2893 static UserCallbackInfo *
2894 internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
2895                                 const struct timeval *relativeTime)
2896 {
2897     struct timeval myRelativeTime;
2898     UserCallbackInfo *p_info;
2899
2900     p_info = (UserCallbackInfo *) malloc (sizeof(UserCallbackInfo));
2901
2902     p_info->p_callback = callback;
2903     p_info->userParam = param;
2904
2905     if (relativeTime == NULL) {
2906         /* treat null parameter as a 0 relative time */
2907         memset (&myRelativeTime, 0, sizeof(myRelativeTime));
2908     } else {
2909         /* FIXME I think event_add's tv param is really const anyway */
2910         memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
2911     }
2912
2913     ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
2914
2915     ril_timer_add(&(p_info->event), &myRelativeTime);
2916
2917     triggerEvLoop();
2918     return p_info;
2919 }
2920
2921
2922 extern "C" void
2923 RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
2924                                 const struct timeval *relativeTime) {
2925     internalRequestTimedCallback (callback, param, relativeTime);
2926 }
2927
2928 const char *
2929 failCauseToString(RIL_Errno e) {
2930     switch(e) {
2931         case RIL_E_SUCCESS: return "E_SUCCESS";
2932         case RIL_E_RADIO_NOT_AVAILABLE: return "E_RAIDO_NOT_AVAILABLE";
2933         case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
2934         case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
2935         case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
2936         case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
2937         case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
2938         case RIL_E_CANCELLED: return "E_CANCELLED";
2939         case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
2940         case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
2941         case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
2942         case RIL_E_SIM_ABSENT:return "E_SIM_ABSENT";
2943         case RIL_E_ILLEGAL_SIM_OR_ME:return "E_ILLEGAL_SIM_OR_ME";
2944 #ifdef FEATURE_MULTIMODE_ANDROID
2945         case RIL_E_SUBSCRIPTION_NOT_AVAILABLE:return "E_SUBSCRIPTION_NOT_AVAILABLE";
2946         case RIL_E_MODE_NOT_SUPPORTED:return "E_MODE_NOT_SUPPORTED";
2947 #endif
2948         default: return "<unknown error>";
2949     }
2950 }
2951
2952 const char *
2953 radioStateToString(RIL_RadioState s) {
2954     switch(s) {
2955         case RADIO_STATE_OFF: return "RADIO_OFF";
2956         case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
2957         case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
2958         case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
2959         case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
2960         case RADIO_STATE_RUIM_NOT_READY:return"RADIO_RUIM_NOT_READY";
2961         case RADIO_STATE_RUIM_READY:return"RADIO_RUIM_READY";
2962         case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:return"RADIO_RUIM_LOCKED_OR_ABSENT";
2963         case RADIO_STATE_NV_NOT_READY:return"RADIO_NV_NOT_READY";
2964         case RADIO_STATE_NV_READY:return"RADIO_NV_READY";
2965         default: return "<unknown state>";
2966     }
2967 }
2968
2969 const char *
2970 callStateToString(RIL_CallState s) {
2971     switch(s) {
2972         case RIL_CALL_ACTIVE : return "ACTIVE";
2973         case RIL_CALL_HOLDING: return "HOLDING";
2974         case RIL_CALL_DIALING: return "DIALING";
2975         case RIL_CALL_ALERTING: return "ALERTING";
2976         case RIL_CALL_INCOMING: return "INCOMING";
2977         case RIL_CALL_WAITING: return "WAITING";
2978         default: return "<unknown state>";
2979     }
2980 }
2981
2982 const char *
2983 requestToString(int request) {
2984 /*
2985  cat libs/telephony/ril_commands.h \
2986  | egrep "^ *{RIL_" \
2987  | sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
2988
2989
2990  cat libs/telephony/ril_unsol_commands.h \
2991  | egrep "^ *{RIL_" \
2992  | sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
2993
2994 */
2995     switch(request) {
2996         case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
2997         case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
2998         case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
2999         case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
3000         case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
3001         case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
3002         case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
3003         case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
3004         case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
3005         case RIL_REQUEST_DIAL: return "DIAL";
3006         case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
3007         case RIL_REQUEST_HANGUP: return "HANGUP";
3008         case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
3009         case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
3010         case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
3011         case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
3012         case RIL_REQUEST_UDUB: return "UDUB";
3013         case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
3014         case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
3015         case RIL_REQUEST_REGISTRATION_STATE: return "REGISTRATION_STATE";
3016         case RIL_REQUEST_GPRS_REGISTRATION_STATE: return "GPRS_REGISTRATION_STATE";
3017         case RIL_REQUEST_OPERATOR: return "OPERATOR";
3018         case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
3019         case RIL_REQUEST_DTMF: return "DTMF";
3020         case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
3021         case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
3022         case RIL_REQUEST_SETUP_DATA_CALL: return "SETUP_DATA_CALL";
3023         case RIL_REQUEST_SIM_IO: return "SIM_IO";
3024         case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
3025         case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
3026         case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
3027         case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
3028         case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
3029         case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
3030         case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
3031         case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
3032         case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
3033         case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
3034         case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
3035         case RIL_REQUEST_ANSWER: return "ANSWER";
3036         case RIL_REQUEST_DEACTIVATE_DATA_CALL: return "DEACTIVATE_DATA_CALL";
3037         case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
3038         case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
3039         case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
3040         case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
3041         case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
3042         case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
3043         case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
3044         case RIL_REQUEST_DTMF_START: return "DTMF_START";
3045         case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
3046         case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
3047         case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
3048         case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
3049         case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
3050         case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
3051         case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
3052         case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
3053         case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
3054         case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: return "LAST_DATA_CALL_FAIL_CAUSE";
3055         case RIL_REQUEST_DATA_CALL_LIST: return "DATA_CALL_LIST";
3056         case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
3057         case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
3058         case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
3059         case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
3060         case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
3061         case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
3062         case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
3063         case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
3064         case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
3065         case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
3066         case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
3067         case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
3068         case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
3069         case RIL_REQUEST_CDMA_SET_SUBSCRIPTION:return"CDMA_SET_SUBSCRIPTION";
3070         case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:return"CDMA_SET_ROAMING_PREFERENCE";
3071         case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:return"CDMA_QUERY_ROAMING_PREFERENCE";
3072         case RIL_REQUEST_SET_TTY_MODE:return"SET_TTY_MODE";
3073         case RIL_REQUEST_QUERY_TTY_MODE:return"QUERY_TTY_MODE";
3074         case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE";
3075         case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE";
3076         case RIL_REQUEST_CDMA_FLASH:return"CDMA_FLASH";
3077         case RIL_REQUEST_CDMA_BURST_DTMF:return"CDMA_BURST_DTMF";
3078         case RIL_REQUEST_CDMA_SEND_SMS:return"CDMA_SEND_SMS";
3079         case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:return"CDMA_SMS_ACKNOWLEDGE";
3080         case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:return"GSM_GET_BROADCAST_SMS_CONFIG";
3081         case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:return"GSM_SET_BROADCAST_SMS_CONFIG";
3082         case RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG:return "CDMA_GET_BROADCAST_SMS_CONFIG";
3083         case RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG:return "CDMA_SET_BROADCAST_SMS_CONFIG";
3084         case RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION:return "CDMA_SMS_BROADCAST_ACTIVATION";
3085         case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: return"CDMA_VALIDATE_AND_WRITE_AKEY";
3086         case RIL_REQUEST_CDMA_SUBSCRIPTION: return"CDMA_SUBSCRIPTION";
3087         case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: return "CDMA_WRITE_SMS_TO_RUIM";
3088         case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: return "CDMA_DELETE_SMS_ON_RUIM";
3089         case RIL_REQUEST_DEVICE_IDENTITY: return "DEVICE_IDENTITY";
3090         case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: return "EXIT_EMERGENCY_CALLBACK_MODE";
3091         case RIL_REQUEST_GET_SMSC_ADDRESS: return "GET_SMSC_ADDRESS";
3092         case RIL_REQUEST_SET_SMSC_ADDRESS: return "SET_SMSC_ADDRESS";
3093         case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: return "REPORT_SMS_MEMORY_STATUS";
3094         case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: return "REPORT_STK_SERVICE_IS_RUNNING";
3095         case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
3096         case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
3097         case RIL_UNSOL_RESPONSE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_NETWORK_STATE_CHANGED";
3098         case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
3099         case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
3100         case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
3101         case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
3102         case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
3103         case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
3104         case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
3105         case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
3106         case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
3107         case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
3108         case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
3109         case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
3110         case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
3111         case RIL_UNSOL_DATA_CALL_LIST_CHANGED: return "UNSOL_DATA_CALL_LIST_CHANGED";
3112         case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
3113         case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED: return "UNSOL_RESPONSE_SIM_STATUS_CHANGED";
3114         case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS: return "UNSOL_NEW_CDMA_SMS";
3115         case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS: return "UNSOL_NEW_BROADCAST_SMS";
3116         case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL: return "UNSOL_CDMA_RUIM_SMS_STORAGE_FULL";
3117         case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "UNSOL_RESTRICTED_STATE_CHANGED";
3118         case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE: return "UNSOL_ENTER_EMERGENCY_CALLBACK_MODE";
3119         case RIL_UNSOL_CDMA_CALL_WAITING: return "UNSOL_CDMA_CALL_WAITING";
3120         case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS: return "UNSOL_CDMA_OTA_PROVISION_STATUS";
3121         case RIL_UNSOL_CDMA_INFO_REC: return "UNSOL_CDMA_INFO_REC";
3122         case RIL_UNSOL_OEM_HOOK_RAW: return "UNSOL_OEM_HOOK_RAW";
3123         case RIL_UNSOL_RINGBACK_TONE: return "UNSOL_RINGBACK_TONE";
3124         case RIL_UNSOL_RESEND_INCALL_MUTE: return "UNSOL_RESEND_INCALL_MUTE";
3125         default: return "<unknown request>";
3126     }
3127 }
3128
3129 } /* namespace android */