ril.cpp revision 31f41943663ccc71bef87d42585b04afb23f6754
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 <cutils/sockets.h>
24#include <cutils/jstring.h>
25#include <cutils/record_stream.h>
26#include <utils/Log.h>
27#include <utils/SystemClock.h>
28#include <pthread.h>
29#include <utils/Parcel.h>
30#include <cutils/jstring.h>
31
32#include <sys/types.h>
33#include <pwd.h>
34
35#include <stdio.h>
36#include <stdlib.h>
37#include <stdarg.h>
38#include <string.h>
39#include <unistd.h>
40#include <fcntl.h>
41#include <time.h>
42#include <errno.h>
43#include <assert.h>
44#include <ctype.h>
45#include <alloca.h>
46#include <sys/un.h>
47#include <assert.h>
48#include <netinet/in.h>
49#include <cutils/properties.h>
50
51#include <ril_event.h>
52
53namespace android {
54
55#define PHONE_PROCESS "radio"
56
57#define SOCKET_NAME_RIL "rild"
58#define SOCKET_NAME_RIL_DEBUG "rild-debug"
59
60#define ANDROID_WAKE_LOCK_NAME "radio-interface"
61
62
63#define PROPERTY_RIL_IMPL "gsm.version.ril-impl"
64
65// match with constant in RIL.java
66#define MAX_COMMAND_BYTES (8 * 1024)
67
68// Basically: memset buffers that the client library
69// shouldn't be using anymore in an attempt to find
70// memory usage issues sooner.
71#define MEMSET_FREED 1
72
73#define NUM_ELEMS(a)     (sizeof (a) / sizeof (a)[0])
74
75/* Constants for response types */
76#define RESPONSE_SOLICITED 0
77#define RESPONSE_UNSOLICITED 1
78
79/* Negative values for private RIL errno's */
80#define RIL_ERRNO_INVALID_RESPONSE -1
81
82// request, response, and unsolicited msg print macro
83#define PRINTBUF_SIZE 8096
84
85// Enable RILC log
86#define RILC_LOG 0
87
88#if RILC_LOG
89    #define startRequest           sprintf(printBuf, "(")
90    #define closeRequest           sprintf(printBuf, "%s)", printBuf)
91    #define printRequest(token, req)           \
92            LOGD("[%04d]> %s %s", token, requestToString(req), printBuf)
93
94    #define startResponse           sprintf(printBuf, "%s {", printBuf)
95    #define closeResponse           sprintf(printBuf, "%s}", printBuf)
96    #define printResponse           LOGD("%s", printBuf)
97
98    #define clearPrintBuf           printBuf[0] = 0
99    #define removeLastChar          printBuf[strlen(printBuf)-1] = 0
100    #define appendPrintBuf(x...)    sprintf(printBuf, x)
101#else
102    #define startRequest
103    #define closeRequest
104    #define printRequest(token, req)
105    #define startResponse
106    #define closeResponse
107    #define printResponse
108    #define clearPrintBuf
109    #define removeLastChar
110    #define appendPrintBuf(x...)
111#endif
112
113enum WakeType {DONT_WAKE, WAKE_PARTIAL};
114
115typedef struct {
116    int requestNumber;
117    void (*dispatchFunction) (Parcel &p, struct RequestInfo *pRI);
118    int(*responseFunction) (Parcel &p, void *response, size_t responselen);
119} CommandInfo;
120
121typedef struct {
122    int requestNumber;
123    int (*responseFunction) (Parcel &p, void *response, size_t responselen);
124    WakeType wakeType;
125} UnsolResponseInfo;
126
127typedef struct RequestInfo {
128    int32_t token;      //this is not RIL_Token
129    CommandInfo *pCI;
130    struct RequestInfo *p_next;
131    char cancelled;
132    char local;         // responses to local commands do not go back to command process
133} RequestInfo;
134
135typedef struct UserCallbackInfo{
136    RIL_TimedCallback p_callback;
137    void *userParam;
138    struct ril_event event;
139    struct UserCallbackInfo *p_next;
140} UserCallbackInfo;
141
142
143/*******************************************************************/
144
145RIL_RadioFunctions s_callbacks = {0, NULL, NULL, NULL, NULL, NULL};
146static int s_registerCalled = 0;
147
148static pthread_t s_tid_dispatch;
149static pthread_t s_tid_reader;
150static int s_started = 0;
151
152static int s_fdListen = -1;
153static int s_fdCommand = -1;
154static int s_fdDebug = -1;
155
156static int s_fdWakeupRead;
157static int s_fdWakeupWrite;
158
159static struct ril_event s_commands_event;
160static struct ril_event s_wakeupfd_event;
161static struct ril_event s_listen_event;
162static struct ril_event s_wake_timeout_event;
163static struct ril_event s_debug_event;
164
165
166static const struct timeval TIMEVAL_WAKE_TIMEOUT = {1,0};
167
168static pthread_mutex_t s_pendingRequestsMutex = PTHREAD_MUTEX_INITIALIZER;
169static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER;
170static pthread_mutex_t s_startupMutex = PTHREAD_MUTEX_INITIALIZER;
171static pthread_cond_t s_startupCond = PTHREAD_COND_INITIALIZER;
172
173static pthread_mutex_t s_dispatchMutex = PTHREAD_MUTEX_INITIALIZER;
174static pthread_cond_t s_dispatchCond = PTHREAD_COND_INITIALIZER;
175
176static RequestInfo *s_pendingRequests = NULL;
177
178static RequestInfo *s_toDispatchHead = NULL;
179static RequestInfo *s_toDispatchTail = NULL;
180
181static UserCallbackInfo *s_last_wake_timeout_info = NULL;
182
183static void *s_lastNITZTimeData = NULL;
184static size_t s_lastNITZTimeDataSize;
185
186#if RILC_LOG
187    static char printBuf[PRINTBUF_SIZE];
188#endif
189
190/*******************************************************************/
191
192static void dispatchVoid (Parcel& p, RequestInfo *pRI);
193static void dispatchString (Parcel& p, RequestInfo *pRI);
194static void dispatchStrings (Parcel& p, RequestInfo *pRI);
195static void dispatchInts (Parcel& p, RequestInfo *pRI);
196static void dispatchDial (Parcel& p, RequestInfo *pRI);
197static void dispatchSIM_IO (Parcel& p, RequestInfo *pRI);
198static void dispatchCallForward(Parcel& p, RequestInfo *pRI);
199static void dispatchRaw(Parcel& p, RequestInfo *pRI);
200static void dispatchSmsWrite (Parcel &p, RequestInfo *pRI);
201
202static int responseInts(Parcel &p, void *response, size_t responselen);
203static int responseStrings(Parcel &p, void *response, size_t responselen);
204static int responseString(Parcel &p, void *response, size_t responselen);
205static int responseVoid(Parcel &p, void *response, size_t responselen);
206static int responseCallList(Parcel &p, void *response, size_t responselen);
207static int responseSMS(Parcel &p, void *response, size_t responselen);
208static int responseSIM_IO(Parcel &p, void *response, size_t responselen);
209static int responseCallForwards(Parcel &p, void *response, size_t responselen);
210static int responseContexts(Parcel &p, void *response, size_t responselen);
211static int responseRaw(Parcel &p, void *response, size_t responselen);
212static int responseSsn(Parcel &p, void *response, size_t responselen);
213static int responseCellList(Parcel &p, void *response, size_t responselen);
214
215extern "C" const char * requestToString(int request);
216extern "C" const char * failCauseToString(RIL_Errno);
217extern "C" const char * callStateToString(RIL_CallState);
218extern "C" const char * radioStateToString(RIL_RadioState);
219
220#ifdef RIL_SHLIB
221extern "C" void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
222                                size_t datalen);
223#endif
224
225static UserCallbackInfo * internalRequestTimedCallback
226    (RIL_TimedCallback callback, void *param,
227        const struct timeval *relativeTime);
228
229/** Index == requestNumber */
230static CommandInfo s_commands[] = {
231#include "ril_commands.h"
232};
233
234static UnsolResponseInfo s_unsolResponses[] = {
235#include "ril_unsol_commands.h"
236};
237
238
239static char *
240strdupReadString(Parcel &p)
241{
242    size_t stringlen;
243    const char16_t *s16;
244
245    s16 = p.readString16Inplace(&stringlen);
246
247    return strndup16to8(s16, stringlen);
248}
249
250static void writeStringToParcel(Parcel &p, const char *s)
251{
252    char16_t *s16;
253    size_t s16_len;
254    s16 = strdup8to16(s, &s16_len);
255    p.writeString16(s16, s16_len);
256    free(s16);
257}
258
259
260static void
261memsetString (char *s)
262{
263    if (s != NULL) {
264        memset (s, 0, strlen(s));
265    }
266}
267
268void   nullParcelReleaseFunction (const uint8_t* data, size_t dataSize,
269                                    const size_t* objects, size_t objectsSize,
270                                        void* cookie)
271{
272    // do nothing -- the data reference lives longer than the Parcel object
273}
274
275/**
276 * To be called from dispatch thread
277 * Issue a single local request, ensuring that the response
278 * is not sent back up to the command process
279 */
280static void
281issueLocalRequest(int request, void *data, int len)
282{
283    RequestInfo *pRI;
284    int ret;
285
286    pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
287
288    pRI->local = 1;
289    pRI->token = 0xffffffff;        // token is not used in this context
290    pRI->pCI = &(s_commands[request]);
291
292    ret = pthread_mutex_lock(&s_pendingRequestsMutex);
293    assert (ret == 0);
294
295    pRI->p_next = s_pendingRequests;
296    s_pendingRequests = pRI;
297
298    ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
299    assert (ret == 0);
300
301    LOGD("C[locl]> %s", requestToString(request));
302
303    s_callbacks.onRequest(request, data, len, pRI);
304}
305
306
307
308static int
309processCommandBuffer(void *buffer, size_t buflen)
310{
311    Parcel p;
312    status_t status;
313    int32_t request;
314    int32_t token;
315    RequestInfo *pRI;
316    int ret;
317
318    p.setData((uint8_t *) buffer, buflen);
319
320    // status checked at end
321    status = p.readInt32(&request);
322    status = p.readInt32 (&token);
323
324    if (status != NO_ERROR) {
325        LOGE("invalid request block");
326        return 0;
327    }
328
329    if (request < 1 || request >= (int32_t)NUM_ELEMS(s_commands)) {
330        LOGE("unsupported request code %d token %d", request, token);
331        // FIXME this should perhaps return a response
332        return 0;
333    }
334
335
336    pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
337
338    pRI->token = token;
339    pRI->pCI = &(s_commands[request]);
340
341    ret = pthread_mutex_lock(&s_pendingRequestsMutex);
342    assert (ret == 0);
343
344    pRI->p_next = s_pendingRequests;
345    s_pendingRequests = pRI;
346
347    ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
348    assert (ret == 0);
349
350/*    sLastDispatchedToken = token; */
351
352    pRI->pCI->dispatchFunction(p, pRI);
353
354    return 0;
355}
356
357static void
358invalidCommandBlock (RequestInfo *pRI)
359{
360    LOGE("invalid command block for token %d request %s",
361                pRI->token, requestToString(pRI->pCI->requestNumber));
362}
363
364/** Callee expects NULL */
365static void
366dispatchVoid (Parcel& p, RequestInfo *pRI)
367{
368    clearPrintBuf;
369    printRequest(pRI->token, pRI->pCI->requestNumber);
370    s_callbacks.onRequest(pRI->pCI->requestNumber, NULL, 0, pRI);
371}
372
373/** Callee expects const char * */
374static void
375dispatchString (Parcel& p, RequestInfo *pRI)
376{
377    status_t status;
378    size_t datalen;
379    size_t stringlen;
380    char *string8 = NULL;
381
382    string8 = strdupReadString(p);
383
384    startRequest;
385    appendPrintBuf("%s%s", printBuf, string8);
386    closeRequest;
387    printRequest(pRI->token, pRI->pCI->requestNumber);
388
389    s_callbacks.onRequest(pRI->pCI->requestNumber, string8,
390                       sizeof(char *), pRI);
391
392#ifdef MEMSET_FREED
393    memsetString(string8);
394#endif
395
396    free(string8);
397    return;
398invalid:
399    invalidCommandBlock(pRI);
400    return;
401}
402
403/** Callee expects const char ** */
404static void
405dispatchStrings (Parcel &p, RequestInfo *pRI)
406{
407    int32_t countStrings;
408    status_t status;
409    size_t datalen;
410    char **pStrings;
411
412    status = p.readInt32 (&countStrings);
413
414    if (status != NO_ERROR) {
415        goto invalid;
416    }
417
418    startRequest;
419    if (countStrings == 0) {
420        // just some non-null pointer
421        pStrings = (char **)alloca(sizeof(char *));
422        datalen = 0;
423    } else if (((int)countStrings) == -1) {
424        pStrings = NULL;
425        datalen = 0;
426    } else {
427        datalen = sizeof(char *) * countStrings;
428
429        pStrings = (char **)alloca(datalen);
430
431        for (int i = 0 ; i < countStrings ; i++) {
432            pStrings[i] = strdupReadString(p);
433            appendPrintBuf("%s%s,", printBuf, pStrings[i]);
434        }
435    }
436    removeLastChar;
437    closeRequest;
438    printRequest(pRI->token, pRI->pCI->requestNumber);
439
440    s_callbacks.onRequest(pRI->pCI->requestNumber, pStrings, datalen, pRI);
441
442    if (pStrings != NULL) {
443        for (int i = 0 ; i < countStrings ; i++) {
444#ifdef MEMSET_FREED
445            memsetString (pStrings[i]);
446#endif
447            free(pStrings[i]);
448        }
449
450#ifdef MEMSET_FREED
451        memset(pStrings, 0, datalen);
452#endif
453    }
454
455    return;
456invalid:
457    invalidCommandBlock(pRI);
458    return;
459}
460
461/** Callee expects const int * */
462static void
463dispatchInts (Parcel &p, RequestInfo *pRI)
464{
465    int32_t count;
466    status_t status;
467    size_t datalen;
468    int *pInts;
469
470    status = p.readInt32 (&count);
471
472    if (status != NO_ERROR || count == 0) {
473        goto invalid;
474    }
475
476    datalen = sizeof(int) * count;
477    pInts = (int *)alloca(datalen);
478
479    startRequest;
480    for (int i = 0 ; i < count ; i++) {
481        int32_t t;
482
483        status = p.readInt32(&t);
484        pInts[i] = (int)t;
485        appendPrintBuf("%s%d,", printBuf, t);
486
487        if (status != NO_ERROR) {
488            goto invalid;
489        }
490   }
491   removeLastChar;
492   closeRequest;
493   printRequest(pRI->token, pRI->pCI->requestNumber);
494
495   s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<int *>(pInts),
496                       datalen, pRI);
497
498#ifdef MEMSET_FREED
499    memset(pInts, 0, datalen);
500#endif
501
502    return;
503invalid:
504    invalidCommandBlock(pRI);
505    return;
506}
507
508
509/**
510 * Callee expects const RIL_SMS_WriteArgs *
511 * Payload is:
512 *   int32_t status
513 *   String pdu
514 */
515static void
516dispatchSmsWrite (Parcel &p, RequestInfo *pRI)
517{
518    RIL_SMS_WriteArgs args;
519    int32_t t;
520    status_t status;
521
522    memset (&args, 0, sizeof(args));
523
524    status = p.readInt32(&t);
525    args.status = (int)t;
526
527    args.pdu = strdupReadString(p);
528
529    if (status != NO_ERROR || args.pdu == NULL) {
530        goto invalid;
531    }
532
533    args.smsc = strdupReadString(p);
534
535    startRequest;
536    appendPrintBuf("%s%d,%s,smsc=%s", printBuf, args.status,
537        (char*)args.pdu,  (char*)args.smsc);
538    closeRequest;
539    printRequest(pRI->token, pRI->pCI->requestNumber);
540
541    s_callbacks.onRequest(pRI->pCI->requestNumber, &args, sizeof(args), pRI);
542
543#ifdef MEMSET_FREED
544    memsetString (args.pdu);
545#endif
546
547    free (args.pdu);
548
549#ifdef MEMSET_FREED
550    memset(&args, 0, sizeof(args));
551#endif
552
553    return;
554invalid:
555    invalidCommandBlock(pRI);
556    return;
557}
558
559/**
560 * Callee expects const RIL_Dial *
561 * Payload is:
562 *   String address
563 *   int32_t clir
564 */
565static void
566dispatchDial (Parcel &p, RequestInfo *pRI)
567{
568    RIL_Dial dial;
569    int32_t t;
570    status_t status;
571
572    memset (&dial, 0, sizeof(dial));
573
574    dial.address = strdupReadString(p);
575
576    status = p.readInt32(&t);
577    dial.clir = (int)t;
578
579    if (status != NO_ERROR || dial.address == NULL) {
580        goto invalid;
581    }
582
583    startRequest;
584    appendPrintBuf("%snum=%s,clir=%d", printBuf, dial.address, dial.clir);
585    closeRequest;
586    printRequest(pRI->token, pRI->pCI->requestNumber);
587
588    s_callbacks.onRequest(pRI->pCI->requestNumber, &dial, sizeof(dial), pRI);
589
590#ifdef MEMSET_FREED
591    memsetString (dial.address);
592#endif
593
594    free (dial.address);
595
596#ifdef MEMSET_FREED
597    memset(&dial, 0, sizeof(dial));
598#endif
599
600    return;
601invalid:
602    invalidCommandBlock(pRI);
603    return;
604}
605
606/**
607 * Callee expects const RIL_SIM_IO *
608 * Payload is:
609 *   int32_t command
610 *   int32_t fileid
611 *   String path
612 *   int32_t p1, p2, p3
613 *   String data
614 *   String pin2
615 */
616static void
617dispatchSIM_IO (Parcel &p, RequestInfo *pRI)
618{
619    RIL_SIM_IO simIO;
620    int32_t t;
621    status_t status;
622
623    memset (&simIO, 0, sizeof(simIO));
624
625    // note we only check status at the end
626
627    status = p.readInt32(&t);
628    simIO.command = (int)t;
629
630    status = p.readInt32(&t);
631    simIO.fileid = (int)t;
632
633    simIO.path = strdupReadString(p);
634
635    status = p.readInt32(&t);
636    simIO.p1 = (int)t;
637
638    status = p.readInt32(&t);
639    simIO.p2 = (int)t;
640
641    status = p.readInt32(&t);
642    simIO.p3 = (int)t;
643
644    simIO.data = strdupReadString(p);
645    simIO.pin2 = strdupReadString(p);
646
647    startRequest;
648    appendPrintBuf("%scmd=0x%X,efid=0x%X,path=%s,%d,%d,%d,%s,pin2=%s", printBuf,
649        simIO.command, simIO.fileid, (char*)simIO.path,
650        simIO.p1, simIO.p2, simIO.p3,
651        (char*)simIO.data,  (char*)simIO.pin2);
652    closeRequest;
653    printRequest(pRI->token, pRI->pCI->requestNumber);
654
655    if (status != NO_ERROR) {
656        goto invalid;
657    }
658
659       s_callbacks.onRequest(pRI->pCI->requestNumber, &simIO, sizeof(simIO), pRI);
660
661#ifdef MEMSET_FREED
662    memsetString (simIO.path);
663    memsetString (simIO.data);
664    memsetString (simIO.pin2);
665#endif
666
667    free (simIO.path);
668    free (simIO.data);
669    free (simIO.pin2);
670
671#ifdef MEMSET_FREED
672    memset(&simIO, 0, sizeof(simIO));
673#endif
674
675    return;
676invalid:
677    invalidCommandBlock(pRI);
678    return;
679}
680
681/**
682 * Callee expects const RIL_CallForwardInfo *
683 * Payload is:
684 *  int32_t status/action
685 *  int32_t reason
686 *  int32_t serviceCode
687 *  int32_t toa
688 *  String number  (0 length -> null)
689 *  int32_t timeSeconds
690 */
691static void
692dispatchCallForward(Parcel &p, RequestInfo *pRI)
693{
694    RIL_CallForwardInfo cff;
695    int32_t t;
696    status_t status;
697
698    memset (&cff, 0, sizeof(cff));
699
700    // note we only check status at the end
701
702    status = p.readInt32(&t);
703    cff.status = (int)t;
704
705    status = p.readInt32(&t);
706    cff.reason = (int)t;
707
708    status = p.readInt32(&t);
709    cff.serviceClass = (int)t;
710
711    status = p.readInt32(&t);
712    cff.toa = (int)t;
713
714    cff.number = strdupReadString(p);
715
716    status = p.readInt32(&t);
717    cff.timeSeconds = (int)t;
718
719    if (status != NO_ERROR) {
720        goto invalid;
721    }
722
723    // special case: number 0-length fields is null
724
725    if (cff.number != NULL && strlen (cff.number) == 0) {
726        cff.number = NULL;
727    }
728
729    startRequest;
730    appendPrintBuf("%sstat=%d,reason=%d,serv=%d,toa=%d,%s,tout=%d", printBuf,
731        cff.status, cff.reason, cff.serviceClass, cff.toa,
732        (char*)cff.number, cff.timeSeconds);
733    closeRequest;
734    printRequest(pRI->token, pRI->pCI->requestNumber);
735
736    s_callbacks.onRequest(pRI->pCI->requestNumber, &cff, sizeof(cff), pRI);
737
738#ifdef MEMSET_FREED
739    memsetString(cff.number);
740#endif
741
742    free (cff.number);
743
744#ifdef MEMSET_FREED
745    memset(&cff, 0, sizeof(cff));
746#endif
747
748    return;
749invalid:
750    invalidCommandBlock(pRI);
751    return;
752}
753
754
755static void
756dispatchRaw(Parcel &p, RequestInfo *pRI)
757{
758    int32_t len;
759    status_t status;
760    const void *data;
761
762    status = p.readInt32(&len);
763
764    if (status != NO_ERROR) {
765        goto invalid;
766    }
767
768    // The java code writes -1 for null arrays
769    if (((int)len) == -1) {
770        data = NULL;
771        len = 0;
772    }
773
774    data = p.readInplace(len);
775
776    startRequest;
777    appendPrintBuf("%sraw_size=%d", printBuf, len);
778    closeRequest;
779    printRequest(pRI->token, pRI->pCI->requestNumber);
780
781    s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<void *>(data), len, pRI);
782
783    return;
784invalid:
785    invalidCommandBlock(pRI);
786    return;
787}
788
789static int
790blockingWrite(int fd, const void *buffer, size_t len)
791{
792    size_t writeOffset = 0;
793    const uint8_t *toWrite;
794
795    toWrite = (const uint8_t *)buffer;
796
797    while (writeOffset < len) {
798        ssize_t written;
799        do {
800            written = write (fd, toWrite + writeOffset,
801                                len - writeOffset);
802        } while (written < 0 && errno == EINTR);
803
804        if (written >= 0) {
805            writeOffset += written;
806        } else {   // written < 0
807            LOGE ("RIL Response: unexpected error on write errno:%d", errno);
808            close(fd);
809            return -1;
810        }
811    }
812
813    return 0;
814}
815
816static int
817sendResponseRaw (const void *data, size_t dataSize)
818{
819    int fd = s_fdCommand;
820    int ret;
821    uint32_t header;
822
823    if (s_fdCommand < 0) {
824        return -1;
825    }
826
827    if (dataSize > MAX_COMMAND_BYTES) {
828        LOGE("RIL: packet larger than %u (%u)",
829                MAX_COMMAND_BYTES, (unsigned int )dataSize);
830
831        return -1;
832    }
833
834
835    // FIXME is blocking here ok? issue #550970
836
837    pthread_mutex_lock(&s_writeMutex);
838
839    header = htonl(dataSize);
840
841    ret = blockingWrite(fd, (void *)&header, sizeof(header));
842
843    if (ret < 0) {
844        return ret;
845    }
846
847    blockingWrite(fd, data, dataSize);
848
849    if (ret < 0) {
850        return ret;
851    }
852
853    pthread_mutex_unlock(&s_writeMutex);
854
855    return 0;
856}
857
858static int
859sendResponse (Parcel &p)
860{
861    printResponse;
862    return sendResponseRaw(p.data(), p.dataSize());
863}
864
865/** response is an int* pointing to an array of ints*/
866
867static int
868responseInts(Parcel &p, void *response, size_t responselen)
869{
870    int numInts;
871
872    if (response == NULL && responselen != 0) {
873        LOGE("invalid response: NULL");
874        return RIL_ERRNO_INVALID_RESPONSE;
875    }
876    if (responselen % sizeof(int) != 0) {
877        LOGE("invalid response length %d expected multiple of %d\n",
878            (int)responselen, (int)sizeof(int));
879        return RIL_ERRNO_INVALID_RESPONSE;
880    }
881
882    int *p_int = (int *) response;
883
884    numInts = responselen / sizeof(int *);
885    p.writeInt32 (numInts);
886
887    /* each int*/
888    startResponse;
889    for (int i = 0 ; i < numInts ; i++) {
890        appendPrintBuf("%s%d,", printBuf, p_int[i]);
891        p.writeInt32(p_int[i]);
892    }
893    removeLastChar;
894    closeResponse;
895
896    return 0;
897}
898
899/** response is a char **, pointing to an array of char *'s */
900static int responseStrings(Parcel &p, void *response, size_t responselen)
901{
902    int numStrings;
903
904    if (response == NULL && responselen != 0) {
905        LOGE("invalid response: NULL");
906        return RIL_ERRNO_INVALID_RESPONSE;
907    }
908    if (responselen % sizeof(char *) != 0) {
909        LOGE("invalid response length %d expected multiple of %d\n",
910            (int)responselen, (int)sizeof(char *));
911        return RIL_ERRNO_INVALID_RESPONSE;
912    }
913
914    if (response == NULL) {
915        p.writeInt32 (0);
916    } else {
917        char **p_cur = (char **) response;
918
919        numStrings = responselen / sizeof(char *);
920        p.writeInt32 (numStrings);
921
922        /* each string*/
923        startResponse;
924        for (int i = 0 ; i < numStrings ; i++) {
925            appendPrintBuf("%s%s,", printBuf, (char*)p_cur[i]);
926            writeStringToParcel (p, p_cur[i]);
927        }
928        removeLastChar;
929        closeResponse;
930    }
931    return 0;
932}
933
934
935/**
936 * NULL strings are accepted
937 * FIXME currently ignores responselen
938 */
939static int responseString(Parcel &p, void *response, size_t responselen)
940{
941    /* one string only */
942    startResponse;
943    appendPrintBuf("%s%s", printBuf, (char*)response);
944    closeResponse;
945
946    writeStringToParcel(p, (const char *)response);
947
948    return 0;
949}
950
951static int responseVoid(Parcel &p, void *response, size_t responselen)
952{
953    startResponse;
954    removeLastChar;
955    return 0;
956}
957
958static int responseCallList(Parcel &p, void *response, size_t responselen)
959{
960    int num;
961
962    if (response == NULL && responselen != 0) {
963        LOGE("invalid response: NULL");
964        return RIL_ERRNO_INVALID_RESPONSE;
965    }
966
967    if (responselen % sizeof (RIL_Call *) != 0) {
968        LOGE("invalid response length %d expected multiple of %d\n",
969            (int)responselen, (int)sizeof (RIL_Call *));
970        return RIL_ERRNO_INVALID_RESPONSE;
971    }
972
973    startResponse;
974    /* number of call info's */
975    num = responselen / sizeof(RIL_Call *);
976    p.writeInt32(num);
977
978    for (int i = 0 ; i < num ; i++) {
979        RIL_Call *p_cur = ((RIL_Call **) response)[i];
980        /* each call info */
981        p.writeInt32(p_cur->state);
982        p.writeInt32(p_cur->index);
983        p.writeInt32(p_cur->toa);
984        p.writeInt32(p_cur->isMpty);
985        p.writeInt32(p_cur->isMT);
986        p.writeInt32(p_cur->als);
987        p.writeInt32(p_cur->isVoice);
988        writeStringToParcel (p, p_cur->number);
989        appendPrintBuf("%s[%s,id=%d,toa=%d,%s,%s,als=%d,%s,%s],", printBuf,
990            callStateToString(p_cur->state),
991            p_cur->index, p_cur->toa,
992            (p_cur->isMpty)?"mpty":"norm",
993            (p_cur->isMT)?"mt":"mo",
994            p_cur->als,
995            (p_cur->isVoice)?"voc":"nonvoc",
996            (char*)p_cur->number);
997    }
998    removeLastChar;
999    closeResponse;
1000
1001    return 0;
1002}
1003
1004static int responseSMS(Parcel &p, void *response, size_t responselen)
1005{
1006    if (response == NULL) {
1007        LOGE("invalid response: NULL");
1008        return RIL_ERRNO_INVALID_RESPONSE;
1009    }
1010
1011    if (responselen != sizeof (RIL_SMS_Response) ) {
1012        LOGE("invalid response length %d expected %d",
1013                (int)responselen, (int)sizeof (RIL_SMS_Response));
1014        return RIL_ERRNO_INVALID_RESPONSE;
1015    }
1016
1017    RIL_SMS_Response *p_cur = (RIL_SMS_Response *) response;
1018
1019    p.writeInt32(p_cur->messageRef);
1020    writeStringToParcel(p, p_cur->ackPDU);
1021
1022    startResponse;
1023    appendPrintBuf("%s%d,%s", printBuf, p_cur->messageRef,
1024        (char*)p_cur->ackPDU);
1025    closeResponse;
1026
1027    return 0;
1028}
1029
1030static int responseContexts(Parcel &p, void *response, size_t responselen)
1031{
1032    if (response == NULL && responselen != 0) {
1033        LOGE("invalid response: NULL");
1034        return RIL_ERRNO_INVALID_RESPONSE;
1035    }
1036
1037    if (responselen % sizeof(RIL_PDP_Context_Response) != 0) {
1038        LOGE("invalid response length %d expected multiple of %d",
1039                (int)responselen, (int)sizeof(RIL_PDP_Context_Response));
1040        return RIL_ERRNO_INVALID_RESPONSE;
1041    }
1042
1043    int num = responselen / sizeof(RIL_PDP_Context_Response);
1044    p.writeInt32(num);
1045
1046    RIL_PDP_Context_Response *p_cur = (RIL_PDP_Context_Response *) response;
1047    startResponse;
1048    int i;
1049    for (i = 0; i < num; i++) {
1050        p.writeInt32(p_cur[i].cid);
1051        p.writeInt32(p_cur[i].active);
1052        writeStringToParcel(p, p_cur[i].type);
1053        writeStringToParcel(p, p_cur[i].apn);
1054        writeStringToParcel(p, p_cur[i].address);
1055        appendPrintBuf("%s[cid=%d,%s,%s,%s,%s],", printBuf,
1056            p_cur[i].cid,
1057            (p_cur[i].active==0)?"down":"up",
1058            (char*)p_cur[i].type,
1059            (char*)p_cur[i].apn,
1060            (char*)p_cur[i].address);
1061    }
1062    removeLastChar;
1063    closeResponse;
1064
1065    return 0;
1066}
1067
1068static int responseRaw(Parcel &p, void *response, size_t responselen)
1069{
1070    if (response == NULL && responselen != 0) {
1071        LOGE("invalid response: NULL with responselen != 0");
1072        return RIL_ERRNO_INVALID_RESPONSE;
1073    }
1074
1075    // The java code reads -1 size as null byte array
1076    if (response == NULL) {
1077        p.writeInt32(-1);
1078    } else {
1079        p.writeInt32(responselen);
1080        p.write(response, responselen);
1081    }
1082
1083    return 0;
1084}
1085
1086
1087static int responseSIM_IO(Parcel &p, void *response, size_t responselen)
1088{
1089    if (response == NULL) {
1090        LOGE("invalid response: NULL");
1091        return RIL_ERRNO_INVALID_RESPONSE;
1092    }
1093
1094    if (responselen != sizeof (RIL_SIM_IO_Response) ) {
1095        LOGE("invalid response length was %d expected %d",
1096                (int)responselen, (int)sizeof (RIL_SIM_IO_Response));
1097        return RIL_ERRNO_INVALID_RESPONSE;
1098    }
1099
1100    RIL_SIM_IO_Response *p_cur = (RIL_SIM_IO_Response *) response;
1101    p.writeInt32(p_cur->sw1);
1102    p.writeInt32(p_cur->sw2);
1103    writeStringToParcel(p, p_cur->simResponse);
1104
1105    startResponse;
1106    appendPrintBuf("%ssw1=0x%X,sw2=0x%X,%s", printBuf, p_cur->sw1, p_cur->sw2,
1107        (char*)p_cur->simResponse);
1108    closeResponse;
1109
1110
1111    return 0;
1112}
1113
1114static int responseCallForwards(Parcel &p, void *response, size_t responselen)
1115{
1116    int num;
1117
1118    if (response == NULL && responselen != 0) {
1119        LOGE("invalid response: NULL");
1120        return RIL_ERRNO_INVALID_RESPONSE;
1121    }
1122
1123    if (responselen % sizeof(RIL_CallForwardInfo *) != 0) {
1124        LOGE("invalid response length %d expected multiple of %d",
1125                (int)responselen, (int)sizeof(RIL_CallForwardInfo *));
1126        return RIL_ERRNO_INVALID_RESPONSE;
1127    }
1128
1129    /* number of call info's */
1130    num = responselen / sizeof(RIL_CallForwardInfo *);
1131    p.writeInt32(num);
1132
1133    startResponse;
1134    for (int i = 0 ; i < num ; i++) {
1135        RIL_CallForwardInfo *p_cur = ((RIL_CallForwardInfo **) response)[i];
1136
1137        p.writeInt32(p_cur->status);
1138        p.writeInt32(p_cur->reason);
1139        p.writeInt32(p_cur->serviceClass);
1140        p.writeInt32(p_cur->toa);
1141        writeStringToParcel(p, p_cur->number);
1142        p.writeInt32(p_cur->timeSeconds);
1143        appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
1144            (p_cur->status==1)?"enable":"disable",
1145            p_cur->reason, p_cur->serviceClass, p_cur->toa,
1146            (char*)p_cur->number,
1147            p_cur->timeSeconds);
1148    }
1149    removeLastChar;
1150    closeResponse;
1151
1152    return 0;
1153}
1154
1155static int responseSsn(Parcel &p, void *response, size_t responselen)
1156{
1157    if (response == NULL) {
1158        LOGE("invalid response: NULL");
1159        return RIL_ERRNO_INVALID_RESPONSE;
1160    }
1161
1162    if (responselen != sizeof(RIL_SuppSvcNotification)) {
1163        LOGE("invalid response length was %d expected %d",
1164                (int)responselen, (int)sizeof (RIL_SuppSvcNotification));
1165        return RIL_ERRNO_INVALID_RESPONSE;
1166    }
1167
1168    RIL_SuppSvcNotification *p_cur = (RIL_SuppSvcNotification *) response;
1169    p.writeInt32(p_cur->notificationType);
1170    p.writeInt32(p_cur->code);
1171    p.writeInt32(p_cur->index);
1172    p.writeInt32(p_cur->type);
1173    writeStringToParcel(p, p_cur->number);
1174
1175    startResponse;
1176    appendPrintBuf("%s%s,code=%d,id=%d,type=%d,%s", printBuf,
1177        (p_cur->notificationType==0)?"mo":"mt",
1178         p_cur->code, p_cur->index, p_cur->type,
1179        (char*)p_cur->number);
1180    closeResponse;
1181
1182    return 0;
1183}
1184
1185static int responseCellList(Parcel &p, void *response, size_t responselen)
1186{
1187    int num;
1188
1189    if (response == NULL && responselen != 0) {
1190        LOGE("invalid response: NULL");
1191        return RIL_ERRNO_INVALID_RESPONSE;
1192    }
1193
1194    if (responselen % sizeof (RIL_NeighboringCell *) != 0) {
1195        LOGE("invalid response length %d expected multiple of %d\n",
1196            (int)responselen, (int)sizeof (RIL_NeighboringCell *));
1197        return RIL_ERRNO_INVALID_RESPONSE;
1198    }
1199
1200    startResponse;
1201    /* number of cell info's */
1202    num = responselen / sizeof(RIL_NeighboringCell *);
1203    p.writeInt32(num);
1204
1205    for (int i = 0 ; i < num ; i++) {
1206        RIL_NeighboringCell *p_cur = ((RIL_NeighboringCell **) response)[i];
1207
1208        /* each cell info */
1209        p.writeInt32(p_cur->rssi);
1210        writeStringToParcel (p, p_cur->cid);
1211
1212        appendPrintBuf("%s[cid=%s,rssi=%d],", printBuf,
1213            p_cur->cid, p_cur->rssi);
1214    }
1215    removeLastChar;
1216    closeResponse;
1217
1218    return 0;
1219}
1220
1221static void triggerEvLoop()
1222{
1223    int ret;
1224    if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
1225        /* trigger event loop to wakeup. No reason to do this,
1226         * if we're in the event loop thread */
1227         do {
1228            ret = write (s_fdWakeupWrite, " ", 1);
1229         } while (ret < 0 && errno == EINTR);
1230    }
1231}
1232
1233static void rilEventAddWakeup(struct ril_event *ev)
1234{
1235    ril_event_add(ev);
1236    triggerEvLoop();
1237}
1238
1239/**
1240 * A write on the wakeup fd is done just to pop us out of select()
1241 * We empty the buffer here and then ril_event will reset the timers on the
1242 * way back down
1243 */
1244static void processWakeupCallback(int fd, short flags, void *param)
1245{
1246    char buff[16];
1247    int ret;
1248
1249    LOGV("processWakeupCallback");
1250
1251    /* empty our wakeup socket out */
1252    do {
1253        ret = read(s_fdWakeupRead, &buff, sizeof(buff));
1254    } while (ret > 0 || (ret < 0 && errno == EINTR));
1255}
1256
1257static void onCommandsSocketClosed()
1258{
1259    int ret;
1260    RequestInfo *p_cur;
1261
1262    /* mark pending requests as "cancelled" so we dont report responses */
1263
1264    ret = pthread_mutex_lock(&s_pendingRequestsMutex);
1265    assert (ret == 0);
1266
1267    p_cur = s_pendingRequests;
1268
1269    for (p_cur = s_pendingRequests
1270            ; p_cur != NULL
1271            ; p_cur  = p_cur->p_next
1272    ) {
1273        p_cur->cancelled = 1;
1274    }
1275
1276    ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
1277    assert (ret == 0);
1278}
1279
1280static void processCommandsCallback(int fd, short flags, void *param)
1281{
1282    RecordStream *p_rs;
1283    void *p_record;
1284    size_t recordlen;
1285    int ret;
1286
1287    assert(fd == s_fdCommand);
1288
1289    p_rs = (RecordStream *)param;
1290
1291    for (;;) {
1292        /* loop until EAGAIN/EINTR, end of stream, or other error */
1293        ret = record_stream_get_next(p_rs, &p_record, &recordlen);
1294
1295        if (ret == 0 && p_record == NULL) {
1296            /* end-of-stream */
1297            break;
1298        } else if (ret < 0) {
1299            break;
1300        } else if (ret == 0) { /* && p_record != NULL */
1301            processCommandBuffer(p_record, recordlen);
1302        }
1303    }
1304
1305    if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
1306        /* fatal error or end-of-stream */
1307        if (ret != 0) {
1308            LOGE("error on reading command socket errno:%d\n", errno);
1309        } else {
1310            LOGW("EOS.  Closing command socket.");
1311        }
1312
1313        close(s_fdCommand);
1314        s_fdCommand = -1;
1315
1316        ril_event_del(&s_commands_event);
1317
1318        record_stream_free(p_rs);
1319
1320        /* start listening for new connections again */
1321        rilEventAddWakeup(&s_listen_event);
1322
1323        onCommandsSocketClosed();
1324    }
1325}
1326
1327
1328static void onNewCommandConnect()
1329{
1330    // implicit radio state changed
1331    RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
1332                                    NULL, 0);
1333
1334    // Send last NITZ time data, in case it was missed
1335    if (s_lastNITZTimeData != NULL) {
1336        sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize);
1337
1338        free(s_lastNITZTimeData);
1339        s_lastNITZTimeData = NULL;
1340    }
1341
1342    // Get version string
1343    if (s_callbacks.getVersion != NULL) {
1344        const char *version;
1345        version = s_callbacks.getVersion();
1346        LOGI("RIL Daemon version: %s\n", version);
1347
1348        property_set(PROPERTY_RIL_IMPL, version);
1349    } else {
1350        LOGI("RIL Daemon version: unavailable\n");
1351        property_set(PROPERTY_RIL_IMPL, "unavailable");
1352    }
1353
1354}
1355
1356static void listenCallback (int fd, short flags, void *param)
1357{
1358    int ret;
1359    int err;
1360    int is_phone_socket;
1361    RecordStream *p_rs;
1362
1363    struct sockaddr_un peeraddr;
1364    socklen_t socklen = sizeof (peeraddr);
1365
1366    struct ucred creds;
1367    socklen_t szCreds = sizeof(creds);
1368
1369    struct passwd *pwd = NULL;
1370
1371    assert (s_fdCommand < 0);
1372    assert (fd == s_fdListen);
1373
1374    s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen);
1375
1376    if (s_fdCommand < 0 ) {
1377        LOGE("Error on accept() errno:%d", errno);
1378        /* start listening for new connections again */
1379        rilEventAddWakeup(&s_listen_event);
1380	return;
1381    }
1382
1383    /* check the credential of the other side and only accept socket from
1384     * phone process
1385     */
1386    errno = 0;
1387    is_phone_socket = 0;
1388
1389    err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
1390
1391    if (err == 0 && szCreds > 0) {
1392      errno = 0;
1393      pwd = getpwuid(creds.uid);
1394      if (pwd != NULL) {
1395	if (strcmp(pwd->pw_name, PHONE_PROCESS) == 0) {
1396	  is_phone_socket = 1;
1397	} else {
1398	  LOGE("RILD can't accept socket from process %s", pwd->pw_name);
1399	}
1400      } else {
1401	LOGE("Error on getpwuid() errno: %d", errno);
1402      }
1403    } else {
1404      LOGD("Error on getsockopt() errno: %d", errno);
1405    }
1406
1407    if ( !is_phone_socket ) {
1408      LOGE("RILD must accept socket from %s", PHONE_PROCESS);
1409
1410      close(s_fdCommand);
1411      s_fdCommand = -1;
1412
1413      onCommandsSocketClosed();
1414
1415      /* start listening for new connections again */
1416      rilEventAddWakeup(&s_listen_event);
1417
1418      return;
1419    }
1420
1421    ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK);
1422
1423    if (ret < 0) {
1424        LOGE ("Error setting O_NONBLOCK errno:%d", errno);
1425    }
1426
1427    LOGI("libril: new connection");
1428
1429    p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES);
1430
1431    ril_event_set (&s_commands_event, s_fdCommand, 1,
1432        processCommandsCallback, p_rs);
1433
1434    rilEventAddWakeup (&s_commands_event);
1435
1436    onNewCommandConnect();
1437}
1438
1439static void freeDebugCallbackArgs(int number, char **args) {
1440    for (int i = 0; i < number; i++) {
1441        if (args[i] != NULL) {
1442            free(args[i]);
1443        }
1444    }
1445    free(args);
1446}
1447
1448static void debugCallback (int fd, short flags, void *param)
1449{
1450    int acceptFD, option;
1451    struct sockaddr_un peeraddr;
1452    socklen_t socklen = sizeof (peeraddr);
1453    int data;
1454    unsigned int qxdm_data[6];
1455    const char *deactData[1] = {"1"};
1456    char *actData[1];
1457    RIL_Dial dialData;
1458    int hangupData[1] = {1};
1459    int number;
1460    char **args;
1461
1462    acceptFD = accept (fd,  (sockaddr *) &peeraddr, &socklen);
1463
1464    if (acceptFD < 0) {
1465        LOGE ("error accepting on debug port: %d\n", errno);
1466        return;
1467    }
1468
1469    if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
1470        LOGE ("error reading on socket: number of Args: \n");
1471        return;
1472    }
1473    args = (char **) malloc(sizeof(char*) * number);
1474
1475    for (int i = 0; i < number; i++) {
1476        int len;
1477        if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
1478            LOGE ("error reading on socket: Len of Args: \n");
1479            freeDebugCallbackArgs(i, args);
1480            return;
1481        }
1482        // +1 for null-term
1483        args[i] = (char *) malloc((sizeof(char) * len) + 1);
1484        if (recv(acceptFD, args[i], sizeof(char) * len, 0)
1485            != sizeof(char) * len) {
1486            LOGE ("error reading on socket: Args[%d] \n", i);
1487            freeDebugCallbackArgs(i, args);
1488            return;
1489        }
1490        char * buf = args[i];
1491        buf[len] = 0;
1492    }
1493
1494    switch (atoi(args[0])) {
1495        case 0:
1496            LOGI ("Connection on debug port: issuing reset.");
1497            issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0);
1498            break;
1499        case 1:
1500            LOGI ("Connection on debug port: issuing radio power off.");
1501            data = 0;
1502            issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
1503            // Close the socket
1504            close(s_fdCommand);
1505            s_fdCommand = -1;
1506            break;
1507        case 2:
1508            LOGI ("Debug port: issuing unsolicited network change.");
1509            RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_NETWORK_STATE_CHANGED,
1510                                      NULL, 0);
1511            break;
1512        case 3:
1513            LOGI ("Debug port: QXDM log enable.");
1514            qxdm_data[0] = 65536;
1515            qxdm_data[1] = 16;
1516            qxdm_data[2] = 1;
1517            qxdm_data[3] = 32;
1518            qxdm_data[4] = 0;
1519            qxdm_data[4] = 8;
1520            issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
1521                              6 * sizeof(int));
1522            break;
1523        case 4:
1524            LOGI ("Debug port: QXDM log disable.");
1525            qxdm_data[0] = 65536;
1526            qxdm_data[1] = 16;
1527            qxdm_data[2] = 0;
1528            qxdm_data[3] = 32;
1529            qxdm_data[4] = 0;
1530            qxdm_data[4] = 8;
1531            issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
1532                              6 * sizeof(int));
1533            break;
1534        case 5:
1535            LOGI("Debug port: Radio On");
1536            data = 1;
1537            issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
1538            sleep(2);
1539            // Set network selection automatic.
1540            issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0);
1541            break;
1542        case 6:
1543            LOGI("Debug port: Setup PDP, Apn :%s\n", args[1]);
1544            actData[0] = args[1];
1545            issueLocalRequest(RIL_REQUEST_SETUP_DEFAULT_PDP, &actData,
1546                              sizeof(actData));
1547            break;
1548        case 7:
1549            LOGI("Debug port: Deactivate PDP");
1550            issueLocalRequest(RIL_REQUEST_DEACTIVATE_DEFAULT_PDP, &deactData,
1551                              sizeof(deactData));
1552            break;
1553        case 8:
1554            LOGI("Debug port: Dial Call");
1555            dialData.clir = 0;
1556            dialData.address = args[1];
1557            issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData));
1558            break;
1559        case 9:
1560            LOGI("Debug port: Answer Call");
1561            issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0);
1562            break;
1563        case 10:
1564            LOGI("Debug port: End Call");
1565            issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
1566                              sizeof(hangupData));
1567            break;
1568        default:
1569            LOGE ("Invalid request");
1570            break;
1571    }
1572    freeDebugCallbackArgs(number, args);
1573    close(acceptFD);
1574}
1575
1576
1577static void userTimerCallback (int fd, short flags, void *param)
1578{
1579    UserCallbackInfo *p_info;
1580
1581    p_info = (UserCallbackInfo *)param;
1582
1583    p_info->p_callback(p_info->userParam);
1584
1585
1586    // FIXME generalize this...there should be a cancel mechanism
1587    if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
1588        s_last_wake_timeout_info = NULL;
1589    }
1590
1591    free(p_info);
1592}
1593
1594
1595static void *
1596eventLoop(void *param)
1597{
1598    int ret;
1599    int filedes[2];
1600
1601    ril_event_init();
1602
1603    pthread_mutex_lock(&s_startupMutex);
1604
1605    s_started = 1;
1606    pthread_cond_broadcast(&s_startupCond);
1607
1608    pthread_mutex_unlock(&s_startupMutex);
1609
1610    ret = pipe(filedes);
1611
1612    if (ret < 0) {
1613        LOGE("Error in pipe() errno:%d", errno);
1614        return NULL;
1615    }
1616
1617    s_fdWakeupRead = filedes[0];
1618    s_fdWakeupWrite = filedes[1];
1619
1620    fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
1621
1622    ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
1623                processWakeupCallback, NULL);
1624
1625    rilEventAddWakeup (&s_wakeupfd_event);
1626
1627    // Only returns on error
1628    ril_event_loop();
1629    LOGE ("error in event_loop_base errno:%d", errno);
1630
1631    return NULL;
1632}
1633
1634extern "C" void
1635RIL_startEventLoop(void)
1636{
1637    int ret;
1638    pthread_attr_t attr;
1639
1640    /* spin up eventLoop thread and wait for it to get started */
1641    s_started = 0;
1642    pthread_mutex_lock(&s_startupMutex);
1643
1644    pthread_attr_init (&attr);
1645    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1646    ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
1647
1648    while (s_started == 0) {
1649        pthread_cond_wait(&s_startupCond, &s_startupMutex);
1650    }
1651
1652    pthread_mutex_unlock(&s_startupMutex);
1653
1654    if (ret < 0) {
1655        LOGE("Failed to create dispatch thread errno:%d", errno);
1656        return;
1657    }
1658}
1659
1660// Used for testing purpose only.
1661extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
1662    memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
1663}
1664
1665extern "C" void
1666RIL_register (const RIL_RadioFunctions *callbacks)
1667{
1668    int ret;
1669    int flags;
1670
1671    if (callbacks == NULL
1672        || ! (callbacks->version == RIL_VERSION || callbacks->version == 1)
1673    ) {
1674        LOGE(
1675            "RIL_register: RIL_RadioFunctions * null or invalid version"
1676            " (expected %d)", RIL_VERSION);
1677        return;
1678    }
1679
1680    if (s_registerCalled > 0) {
1681        LOGE("RIL_register has been called more than once. "
1682                "Subsequent call ignored");
1683        return;
1684    }
1685
1686    memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
1687
1688    s_registerCalled = 1;
1689
1690    // Little self-check
1691
1692    for (int i = 0; i < (int)NUM_ELEMS(s_commands) ; i++) {
1693        assert(i == s_commands[i].requestNumber);
1694    }
1695
1696    for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses) ; i++) {
1697        assert(i + RIL_UNSOL_RESPONSE_BASE
1698                == s_unsolResponses[i].requestNumber);
1699    }
1700
1701    // New rild impl calls RIL_startEventLoop() first
1702    // old standalone impl wants it here.
1703
1704    if (s_started == 0) {
1705        RIL_startEventLoop();
1706    }
1707
1708    // start listen socket
1709
1710#if 0
1711    ret = socket_local_server (SOCKET_NAME_RIL,
1712            ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1713
1714    if (ret < 0) {
1715        LOGE("Unable to bind socket errno:%d", errno);
1716        exit (-1);
1717    }
1718    s_fdListen = ret;
1719
1720#else
1721    s_fdListen = android_get_control_socket(SOCKET_NAME_RIL);
1722    if (s_fdListen < 0) {
1723        LOGE("Failed to get socket '" SOCKET_NAME_RIL "'");
1724        exit(-1);
1725    }
1726
1727    ret = listen(s_fdListen, 4);
1728
1729    if (ret < 0) {
1730        LOGE("Failed to listen on control socket '%d': %s",
1731             s_fdListen, strerror(errno));
1732        exit(-1);
1733    }
1734#endif
1735
1736
1737    /* note: non-persistent so we can accept only one connection at a time */
1738    ril_event_set (&s_listen_event, s_fdListen, false,
1739                listenCallback, NULL);
1740
1741    rilEventAddWakeup (&s_listen_event);
1742
1743#if 1
1744    // start debug interface socket
1745
1746    s_fdDebug = android_get_control_socket(SOCKET_NAME_RIL_DEBUG);
1747    if (s_fdDebug < 0) {
1748        LOGE("Failed to get socket '" SOCKET_NAME_RIL_DEBUG "' errno:%d", errno);
1749        exit(-1);
1750    }
1751
1752    ret = listen(s_fdDebug, 4);
1753
1754    if (ret < 0) {
1755        LOGE("Failed to listen on ril debug socket '%d': %s",
1756             s_fdDebug, strerror(errno));
1757        exit(-1);
1758    }
1759
1760    ril_event_set (&s_debug_event, s_fdDebug, true,
1761                debugCallback, NULL);
1762
1763    rilEventAddWakeup (&s_debug_event);
1764#endif
1765
1766}
1767
1768static int
1769checkAndDequeueRequestInfo(struct RequestInfo *pRI)
1770{
1771    int ret = 0;
1772
1773    if (pRI == NULL) {
1774        return 0;
1775    }
1776
1777    pthread_mutex_lock(&s_pendingRequestsMutex);
1778
1779    for(RequestInfo **ppCur = &s_pendingRequests
1780        ; *ppCur != NULL
1781        ; ppCur = &((*ppCur)->p_next)
1782    ) {
1783        if (pRI == *ppCur) {
1784            ret = 1;
1785
1786            *ppCur = (*ppCur)->p_next;
1787            break;
1788        }
1789    }
1790
1791    pthread_mutex_unlock(&s_pendingRequestsMutex);
1792
1793    return ret;
1794}
1795
1796
1797extern "C" void
1798RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen)
1799{
1800    RequestInfo *pRI;
1801    int ret;
1802    size_t errorOffset;
1803
1804    pRI = (RequestInfo *)t;
1805
1806    if (!checkAndDequeueRequestInfo(pRI)) {
1807        LOGE ("RIL_onRequestComplete: invalid RIL_Token");
1808        return;
1809    }
1810
1811    if (pRI->local > 0) {
1812        // Locally issued command...void only!
1813        // response does not go back up the command socket
1814        LOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
1815
1816        goto done;
1817    }
1818
1819    appendPrintBuf("[%04d]< %s",
1820        pRI->token, requestToString(pRI->pCI->requestNumber));
1821
1822    if (pRI->cancelled == 0) {
1823        Parcel p;
1824
1825        p.writeInt32 (RESPONSE_SOLICITED);
1826        p.writeInt32 (pRI->token);
1827        errorOffset = p.dataPosition();
1828
1829        p.writeInt32 (e);
1830
1831        if (e == RIL_E_SUCCESS) {
1832            /* process response on success */
1833            ret = pRI->pCI->responseFunction(p, response, responselen);
1834
1835            /* if an error occurred, rewind and mark it */
1836            if (ret != 0) {
1837                p.setDataPosition(errorOffset);
1838                p.writeInt32 (ret);
1839            }
1840        } else {
1841            appendPrintBuf("%s returns %s", printBuf, failCauseToString(e));
1842        }
1843
1844        if (s_fdCommand < 0) {
1845            LOGD ("RIL onRequestComplete: Command channel closed");
1846        }
1847        sendResponse(p);
1848    }
1849
1850done:
1851    free(pRI);
1852}
1853
1854
1855static void
1856grabPartialWakeLock()
1857{
1858    acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
1859}
1860
1861static void
1862releaseWakeLock()
1863{
1864    release_wake_lock(ANDROID_WAKE_LOCK_NAME);
1865}
1866
1867/**
1868 * Timer callback to put us back to sleep before the default timeout
1869 */
1870static void
1871wakeTimeoutCallback (void *param)
1872{
1873    // We're using "param != NULL" as a cancellation mechanism
1874    if (param == NULL) {
1875        //LOGD("wakeTimeout: releasing wake lock");
1876
1877        releaseWakeLock();
1878    } else {
1879        //LOGD("wakeTimeout: releasing wake lock CANCELLED");
1880    }
1881}
1882
1883extern "C"
1884void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
1885                                size_t datalen)
1886{
1887    int unsolResponseIndex;
1888    int ret;
1889    int64_t timeReceived = 0;
1890    bool shouldScheduleTimeout = false;
1891
1892    if (s_registerCalled == 0) {
1893        // Ignore RIL_onUnsolicitedResponse before RIL_register
1894        LOGW("RIL_onUnsolicitedResponse called before RIL_register");
1895        return;
1896    }
1897
1898    unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
1899
1900    if ((unsolResponseIndex < 0)
1901        || (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
1902        LOGE("unsupported unsolicited response code %d", unsolResponse);
1903        return;
1904    }
1905
1906    // Grab a wake lock if needed for this reponse,
1907    // as we exit we'll either release it immediately
1908    // or set a timer to release it later.
1909    switch (s_unsolResponses[unsolResponseIndex].wakeType) {
1910        case WAKE_PARTIAL:
1911            grabPartialWakeLock();
1912            shouldScheduleTimeout = true;
1913        break;
1914
1915        case DONT_WAKE:
1916        default:
1917            // No wake lock is grabed so don't set timeout
1918            shouldScheduleTimeout = false;
1919            break;
1920    }
1921
1922    // Mark the time this was received, doing this
1923    // after grabing the wakelock incase getting
1924    // the elapsedRealTime might cause us to goto
1925    // sleep.
1926    if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
1927        timeReceived = elapsedRealtime();
1928    }
1929
1930    appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
1931
1932    Parcel p;
1933
1934    p.writeInt32 (RESPONSE_UNSOLICITED);
1935    p.writeInt32 (unsolResponse);
1936
1937    ret = s_unsolResponses[unsolResponseIndex]
1938                .responseFunction(p, data, datalen);
1939    if (ret != 0) {
1940        // Problem with the response. Don't continue;
1941        goto error_exit;
1942    }
1943
1944    // some things get more payload
1945    switch(unsolResponse) {
1946        case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
1947            p.writeInt32(s_callbacks.onStateRequest());
1948            appendPrintBuf("%s {%s}", printBuf,
1949                radioStateToString(s_callbacks.onStateRequest()));
1950        break;
1951
1952
1953        case RIL_UNSOL_NITZ_TIME_RECEIVED:
1954            // Store the time that this was received so the
1955            // handler of this message can account for
1956            // the time it takes to arrive and process. In
1957            // particular the system has been known to sleep
1958            // before this message can be processed.
1959            p.writeInt64(timeReceived);
1960        break;
1961    }
1962
1963    ret = sendResponse(p);
1964    if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
1965
1966        // Unfortunately, NITZ time is not poll/update like everything
1967        // else in the system. So, if the upstream client isn't connected,
1968        // keep a copy of the last NITZ response (with receive time noted
1969        // above) around so we can deliver it when it is connected
1970
1971        if (s_lastNITZTimeData != NULL) {
1972            free (s_lastNITZTimeData);
1973            s_lastNITZTimeData = NULL;
1974        }
1975
1976        s_lastNITZTimeData = malloc(p.dataSize());
1977        s_lastNITZTimeDataSize = p.dataSize();
1978        memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
1979    }
1980
1981    // For now, we automatically go back to sleep after TIMEVAL_WAKE_TIMEOUT
1982    // FIXME The java code should handshake here to release wake lock
1983
1984    if (shouldScheduleTimeout) {
1985        // Cancel the previous request
1986        if (s_last_wake_timeout_info != NULL) {
1987            s_last_wake_timeout_info->userParam = (void *)1;
1988        }
1989
1990        s_last_wake_timeout_info
1991            = internalRequestTimedCallback(wakeTimeoutCallback, NULL,
1992                                            &TIMEVAL_WAKE_TIMEOUT);
1993    }
1994
1995    // Normal exit
1996    return;
1997
1998error_exit:
1999    // There was an error and we've got the wake lock so release it.
2000    if (shouldScheduleTimeout) {
2001        releaseWakeLock();
2002    }
2003}
2004
2005/** FIXME generalize this if you track UserCAllbackInfo, clear it
2006    when the callback occurs
2007*/
2008static UserCallbackInfo *
2009internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
2010                                const struct timeval *relativeTime)
2011
2012{
2013    struct timeval myRelativeTime;
2014    UserCallbackInfo *p_info;
2015
2016    p_info = (UserCallbackInfo *) malloc (sizeof(UserCallbackInfo));
2017
2018    p_info->p_callback = callback;
2019    p_info->userParam = param;
2020
2021    if (relativeTime == NULL) {
2022        /* treat null parameter as a 0 relative time */
2023        memset (&myRelativeTime, 0, sizeof(myRelativeTime));
2024    } else {
2025        /* FIXME I think event_add's tv param is really const anyway */
2026        memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
2027    }
2028
2029    ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
2030
2031    ril_timer_add(&(p_info->event), &myRelativeTime);
2032
2033    triggerEvLoop();
2034    return p_info;
2035}
2036
2037
2038extern "C" void
2039RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
2040                                const struct timeval *relativeTime)
2041{
2042    internalRequestTimedCallback (callback, param, relativeTime);
2043}
2044
2045const char *
2046failCauseToString(RIL_Errno e)
2047{
2048    switch(e) {
2049        case RIL_E_SUCCESS: return "E_SUCCESS";
2050        case RIL_E_RADIO_NOT_AVAILABLE: return "E_RAIDO_NOT_AVAILABLE";
2051        case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
2052        case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
2053        case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
2054        case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
2055        case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
2056        case RIL_E_CANCELLED: return "E_CANCELLED";
2057        case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
2058        case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
2059        case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
2060        default: return "<unknown error>";
2061    }
2062}
2063
2064const char *
2065radioStateToString(RIL_RadioState s)
2066{
2067    switch(s) {
2068        case RADIO_STATE_OFF: return "RADIO_OFF";
2069        case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
2070        case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
2071        case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
2072        case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
2073        default: return "<unknown state>";
2074    }
2075}
2076
2077const char *
2078callStateToString(RIL_CallState s)
2079{
2080    switch(s) {
2081        case RIL_CALL_ACTIVE : return "ACTIVE";
2082        case RIL_CALL_HOLDING: return "HOLDING";
2083        case RIL_CALL_DIALING: return "DIALING";
2084        case RIL_CALL_ALERTING: return "ALERTING";
2085        case RIL_CALL_INCOMING: return "INCOMING";
2086        case RIL_CALL_WAITING: return "WAITING";
2087        default: return "<unknown state>";
2088    }
2089}
2090
2091const char *
2092requestToString(int request)
2093{
2094/*
2095 cat libs/telephony/ril_commands.h \
2096 | egrep "^ *{RIL_" \
2097 | sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
2098
2099
2100 cat libs/telephony/ril_unsol_commands.h \
2101 | egrep "^ *{RIL_" \
2102 | sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
2103
2104*/
2105    switch(request) {
2106        case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
2107        case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
2108        case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
2109        case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
2110        case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
2111        case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
2112        case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
2113        case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
2114        case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
2115        case RIL_REQUEST_DIAL: return "DIAL";
2116        case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
2117        case RIL_REQUEST_HANGUP: return "HANGUP";
2118        case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
2119        case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
2120        case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
2121        case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
2122        case RIL_REQUEST_UDUB: return "UDUB";
2123        case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
2124        case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
2125        case RIL_REQUEST_REGISTRATION_STATE: return "REGISTRATION_STATE";
2126        case RIL_REQUEST_GPRS_REGISTRATION_STATE: return "GPRS_REGISTRATION_STATE";
2127        case RIL_REQUEST_OPERATOR: return "OPERATOR";
2128        case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
2129        case RIL_REQUEST_DTMF: return "DTMF";
2130        case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
2131        case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
2132        case RIL_REQUEST_SETUP_DEFAULT_PDP: return "SETUP_DEFAULT_PDP";
2133        case RIL_REQUEST_SIM_IO: return "SIM_IO";
2134        case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
2135        case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
2136        case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
2137        case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
2138        case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
2139        case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
2140        case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
2141        case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
2142        case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
2143        case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
2144        case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
2145        case RIL_REQUEST_ANSWER: return "ANSWER";
2146        case RIL_REQUEST_DEACTIVATE_DEFAULT_PDP: return "DEACTIVATE_DEFAULT_PDP";
2147        case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
2148        case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
2149        case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
2150        case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
2151        case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
2152        case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
2153        case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
2154        case RIL_REQUEST_DTMF_START: return "DTMF_START";
2155        case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
2156        case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
2157        case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
2158        case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
2159        case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
2160        case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
2161        case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
2162        case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
2163        case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
2164        case RIL_REQUEST_LAST_PDP_FAIL_CAUSE: return "LAST_PDP_FAIL_CAUSE";
2165        case RIL_REQUEST_PDP_CONTEXT_LIST: return "PDP_CONTEXT_LIST";
2166        case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
2167        case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
2168        case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
2169	    case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
2170	    case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
2171        case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
2172        case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
2173        case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
2174        case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
2175        case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
2176        case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
2177        case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
2178        case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
2179
2180        case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
2181        case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
2182        case RIL_UNSOL_RESPONSE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_NETWORK_STATE_CHANGED";
2183        case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
2184        case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
2185        case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
2186        case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
2187        case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
2188        case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
2189        case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
2190        case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
2191        case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
2192        case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
2193        case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
2194        case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
2195        case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
2196        case RIL_UNSOL_PDP_CONTEXT_LIST_CHANGED: return "UNSOL_PDP_CONTEXT_LIST_CHANGED";
2197        case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
2198        default: return "<unknown request>";
2199    }
2200}
2201
2202} /* namespace android */
2203