OSDN Git Service

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