OSDN Git Service

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