Home | History | Annotate | Download | only in ril
      1 /*
      2 ** Copyright 2017, The Android Open Source Project
      3 **
      4 ** Licensed under the Apache License, Version 2.0 (the "License");
      5 ** you may not use this file except in compliance with the License.
      6 ** You may obtain a copy of the License at
      7 **
      8 **     http://www.apache.org/licenses/LICENSE-2.0
      9 **
     10 ** Unless required by applicable law or agreed to in writing, software
     11 ** distributed under the License ioogle/s distributed on an "AS IS" BASIS,
     12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13 ** See the License for the specific language governing permissions and
     14 ** limitations under the License.
     15 */
     16 
     17 #include "guest/hals/ril/vsoc_ril.h"
     18 
     19 #include <cutils/properties.h>
     20 #include <string.h>
     21 #include <sys/types.h>
     22 #include <time.h>
     23 
     24 #include <map>
     25 #include <set>
     26 #include <string>
     27 #include <vector>
     28 
     29 #include "common/libs/net/netlink_client.h"
     30 #include "common/libs/net/network_interface.h"
     31 #include "common/libs/net/network_interface_manager.h"
     32 #include "common/vsoc/lib/ril_region_view.h"
     33 #include "guest/libs/platform_support/api_level_fixes.h"
     34 
     35 #define VSOC_RIL_VERSION_STRING "Android VSoC RIL 1.0"
     36 
     37 /* Modem Technology bits */
     38 #define MDM_GSM 0x01
     39 #define MDM_WCDMA 0x02
     40 #define MDM_CDMA 0x04
     41 #define MDM_EVDO 0x08
     42 #define MDM_LTE 0x10
     43 
     44 #if VSOC_PLATFORM_SDK_BEFORE(K)
     45 #define RADIO_TECH_3GPP 1
     46 #define RADIO_TECH_3GPP2 2
     47 #endif
     48 
     49 typedef enum {
     50   SIM_ABSENT = 0,
     51   SIM_NOT_READY = 1,
     52   SIM_READY = 2,  // SIM_READY means the radio state is RADIO_STATE_SIM_READY
     53   SIM_PIN = 3,
     54   SIM_PUK = 4,
     55   SIM_NETWORK_PERSONALIZATION = 5,
     56   RUIM_ABSENT = 6,
     57   RUIM_NOT_READY = 7,
     58   RUIM_READY = 8,
     59   RUIM_PIN = 9,
     60   RUIM_PUK = 10,
     61   RUIM_NETWORK_PERSONALIZATION = 11
     62 } SIM_Status;
     63 
     64 static const struct RIL_Env* gce_ril_env;
     65 
     66 static const struct timeval TIMEVAL_SIMPOLL = {3, 0};
     67 
     68 static time_t gce_ril_start_time;
     69 
     70 static void pollSIMState(void* param);
     71 
     72 RIL_RadioState gRadioPowerState = RADIO_STATE_OFF;
     73 
     74 struct DataCall {
     75   enum AllowedAuthenticationType { kNone = 0, kPap = 1, kChap = 2, kBoth = 3 };
     76 
     77   enum ConnectionType {
     78     kConnTypeIPv4,
     79     kConnTypeIPv6,
     80     kConnTypeIPv4v6,
     81     kConnTypePPP
     82   };
     83 
     84   enum LinkState {
     85     kLinkStateInactive = 0,
     86     kLinkStateDown = 1,
     87     kLinkStateUp = 2,
     88   };
     89 
     90   RIL_RadioTechnology technology_;
     91   RIL_DataProfile profile_;
     92   std::string access_point_;
     93   std::string username_;
     94   std::string password_;
     95   AllowedAuthenticationType auth_type_;
     96   ConnectionType connection_type_;
     97   LinkState link_state_;
     98   RIL_DataCallFailCause fail_cause_;
     99   std::string other_properties_;
    100 };
    101 
    102 static std::string gSimPIN = "0000";
    103 static const std::string gSimPUK = "11223344";
    104 static int gSimPINAttempts = 0;
    105 static const int gSimPINAttemptsMax = 3;
    106 static SIM_Status gSimStatus = SIM_NOT_READY;
    107 
    108 // SetUpNetworkInterface configures IP and Broadcast addresses on a RIL
    109 // controlled network interface.
    110 // This call returns true, if operation was successful.
    111 bool SetUpNetworkInterface(const char* ipaddr, int prefixlen,
    112                            const char* bcaddr) {
    113   auto factory = cvd::NetlinkClientFactory::Default();
    114   std::unique_ptr<cvd::NetlinkClient> nl(factory->New(NETLINK_ROUTE));
    115   std::unique_ptr<cvd::NetworkInterfaceManager> nm(
    116       cvd::NetworkInterfaceManager::New(factory));
    117   std::unique_ptr<cvd::NetworkInterface> ni(nm->Open("rmnet0", "eth0"));
    118 
    119   if (ni) {
    120     ni->SetName("rmnet0");
    121     ni->SetAddress(ipaddr);
    122     ni->SetBroadcastAddress(bcaddr);
    123     ni->SetPrefixLength(prefixlen);
    124     ni->SetOperational(true);
    125     bool res = nm->ApplyChanges(*ni);
    126     if (!res) ALOGE("Could not configure rmnet0");
    127     return res;
    128   }
    129   return false;
    130 }
    131 
    132 // TearDownNetworkInterface disables network interface.
    133 // This call returns true, if operation was successful.
    134 bool TearDownNetworkInterface() {
    135   auto nm(cvd::NetworkInterfaceManager::New(nullptr));
    136   auto ni(nm->Open("rmnet0", "eth0"));
    137 
    138   if (ni) {
    139     ni->SetOperational(false);
    140     bool res = nm->ApplyChanges(*ni);
    141     if (!res) ALOGE("Could not disable rmnet0");
    142     return res;
    143   }
    144   return false;
    145 }
    146 
    147 static int gNextDataCallId = 8;
    148 static std::map<int, DataCall> gDataCalls;
    149 static bool gRilConnected = false;
    150 
    151 static int request_or_send_data_calllist(RIL_Token* t) {
    152 #if VSOC_PLATFORM_SDK_AFTER(N_MR1)
    153   RIL_Data_Call_Response_v11* responses =
    154       new RIL_Data_Call_Response_v11[gDataCalls.size()];
    155 #else
    156   RIL_Data_Call_Response_v6* responses =
    157       new RIL_Data_Call_Response_v6[gDataCalls.size()];
    158 #endif
    159 
    160   int index = 0;
    161 
    162   ALOGV("Query data call list: %zu data calls tracked.", gDataCalls.size());
    163 
    164   for (std::map<int, DataCall>::iterator iter = gDataCalls.begin();
    165        iter != gDataCalls.end(); ++iter, ++index) {
    166     responses[index].status = iter->second.fail_cause_;
    167     responses[index].suggestedRetryTime = -1;
    168     responses[index].cid = iter->first;
    169     responses[index].active = iter->second.link_state_;
    170 
    171     switch (iter->second.connection_type_) {
    172       case DataCall::kConnTypeIPv4:
    173         responses[index].type = (char*)"IP";
    174         break;
    175       case DataCall::kConnTypeIPv6:
    176         responses[index].type = (char*)"IPV6";
    177         break;
    178       case DataCall::kConnTypeIPv4v6:
    179         responses[index].type = (char*)"IPV4V6";
    180         break;
    181       case DataCall::kConnTypePPP:
    182         responses[index].type = (char*)"PPP";
    183         break;
    184       default:
    185         responses[index].type = (char*)"IP";
    186         break;
    187     }
    188 
    189     auto ril_region_view = vsoc::ril::RilRegionView::GetInstance();
    190 
    191     responses[index].ifname = (char*)"rmnet0";
    192     responses[index].addresses =
    193       const_cast<char*>(ril_region_view->address_and_prefix_length());
    194     responses[index].dnses = (char*)ril_region_view->data()->dns;
    195     responses[index].gateways = (char*)ril_region_view->data()->gateway;
    196 #if VSOC_PLATFORM_SDK_AFTER(N_MR1)
    197     responses[index].pcscf = (char*)"";
    198     responses[index].mtu = 1440;
    199 #endif
    200   }
    201 
    202   bool new_conn_state = (gDataCalls.size() > 0);
    203 
    204   if (gRilConnected != new_conn_state) {
    205     time_t curr_time;
    206     time(&curr_time);
    207     double diff_in_secs = difftime(curr_time, gce_ril_start_time);
    208 
    209     gRilConnected = new_conn_state;
    210 
    211     if (new_conn_state) {
    212       ALOGV("MOBILE_DATA_CONNECTED %.2lf seconds", diff_in_secs);
    213     } else {
    214       ALOGV("MOBILE_DATA_DISCONNECTED %.2lf seconds", diff_in_secs);
    215     }
    216 
    217     if (property_set("ril.net_connected", new_conn_state ? "1" : "0")) {
    218       ALOGE("Couldn't set a system property ril.net_connected.");
    219     }
    220   }
    221 
    222   if (t != NULL) {
    223     gce_ril_env->OnRequestComplete(*t, RIL_E_SUCCESS, responses,
    224                                    gDataCalls.size() * sizeof(*responses));
    225   } else {
    226     gce_ril_env->OnUnsolicitedResponse(RIL_UNSOL_DATA_CALL_LIST_CHANGED,
    227                                        responses,
    228                                        gDataCalls.size() * sizeof(*responses));
    229   }
    230   delete[] responses;
    231   return 0;
    232 }
    233 
    234 static void request_datacall_fail_cause(RIL_Token t) {
    235   RIL_DataCallFailCause fail = PDP_FAIL_DATA_REGISTRATION_FAIL;
    236 
    237   if (gDataCalls.size() > 0) {
    238     fail = gDataCalls.rbegin()->second.fail_cause_;
    239   }
    240 
    241   ALOGV("Requesting last data call setup fail cause (%d)", fail);
    242   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &fail, sizeof(fail));
    243 };
    244 
    245 static void request_data_calllist(void* /*data*/, size_t /*datalen*/,
    246                                   RIL_Token t) {
    247   request_or_send_data_calllist(&t);
    248 }
    249 
    250 static void request_setup_data_call(void* data, size_t datalen, RIL_Token t) {
    251   char** details = static_cast<char**>(data);
    252   const size_t fields = datalen / sizeof(details[0]);
    253 
    254   // There are two different versions of this interface, one providing 7 strings
    255   // and the other providing 8. The code below will assume the presence of 7
    256   // strings in all cases, so bail out here if things appear to be wrong. We
    257   // protect the 8 string case below.
    258   if (fields < 7) {
    259     ALOGE("%s returning: called with small datalen %zu", __FUNCTION__, datalen);
    260     return;
    261   }
    262   DataCall call;
    263   int tech = atoi(details[0]);
    264   switch (tech) {
    265     case 0:
    266     case 2 + RADIO_TECH_1xRTT:
    267       call.technology_ = RADIO_TECH_1xRTT;
    268       break;
    269 
    270     case 1:
    271     case 2 + RADIO_TECH_EDGE:
    272       call.technology_ = RADIO_TECH_EDGE;
    273       break;
    274 
    275     default:
    276       call.technology_ = RIL_RadioTechnology(tech - 2);
    277       break;
    278   }
    279 
    280   int profile = atoi(details[1]);
    281   call.profile_ = RIL_DataProfile(profile);
    282 
    283   if (details[2]) call.access_point_ = details[2];
    284   if (details[3]) call.username_ = details[3];
    285   if (details[4]) call.password_ = details[4];
    286 
    287   int auth_type = atoi(details[5]);
    288   call.auth_type_ = DataCall::AllowedAuthenticationType(auth_type);
    289 
    290   if (!strcmp("IP", details[6])) {
    291     call.connection_type_ = DataCall::kConnTypeIPv4;
    292   } else if (!strcmp("IPV6", details[6])) {
    293     call.connection_type_ = DataCall::kConnTypeIPv6;
    294   } else if (!strcmp("IPV4V6", details[6])) {
    295     call.connection_type_ = DataCall::kConnTypeIPv4v6;
    296   } else if (!strcmp("PPP", details[6])) {
    297     call.connection_type_ = DataCall::kConnTypePPP;
    298   } else {
    299     ALOGW("Unknown / unsupported connection type %s. Falling back to IPv4",
    300           details[6]);
    301     call.connection_type_ = DataCall::kConnTypeIPv4;
    302   }
    303 
    304   if (call.connection_type_ != DataCall::kConnTypeIPv4) {
    305     ALOGE("Non-IPv4 connections are not supported by VSOC RIL.");
    306     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
    307     return;
    308   }
    309 
    310   call.link_state_ = DataCall::kLinkStateUp;
    311   call.fail_cause_ = PDP_FAIL_NONE;
    312   if (fields > 7) {
    313     if (details[7]) call.other_properties_ = details[7];
    314   }
    315 
    316   if (gDataCalls.empty()) {
    317     auto ril_region_view = vsoc::ril::RilRegionView::GetInstance();
    318     SetUpNetworkInterface(ril_region_view->data()->ipaddr,
    319                           ril_region_view->data()->prefixlen,
    320                           ril_region_view->data()->broadcast);
    321   }
    322 
    323   gDataCalls[gNextDataCallId] = call;
    324   gNextDataCallId++;
    325 
    326   ALOGV("Requesting data call setup to APN %s, technology %s, prof %s",
    327         details[2], details[0], details[1]);
    328 
    329   request_or_send_data_calllist(&t);
    330 
    331   gRilConnected = (gDataCalls.size() > 0);
    332 }
    333 
    334 static void request_teardown_data_call(void* data, size_t /*datalen*/,
    335                                        RIL_Token t) {
    336   char** data_strs = (char**)data;
    337   int call_id = atoi(data_strs[0]);
    338   int reason = atoi(data_strs[1]);
    339 
    340   ALOGV("Tearing down data call %d, reason: %d", call_id, reason);
    341 
    342   gDataCalls.erase(call_id);
    343   gRilConnected = (gDataCalls.size() > 0);
    344 
    345   if (!gRilConnected) {
    346     TearDownNetworkInterface();
    347   }
    348   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    349 }
    350 
    351 static void set_radio_state(RIL_RadioState new_state, RIL_Token t) {
    352   // From header:
    353   // Toggle radio on and off (for "airplane" mode)
    354   // If the radio is is turned off/on the radio modem subsystem
    355   // is expected return to an initialized state. For instance,
    356   // any voice and data calls will be terminated and all associated
    357   // lists emptied.
    358   gDataCalls.clear();
    359 
    360   gSimStatus = SIM_NOT_READY;
    361   ALOGV("RIL_RadioState change %d to %d", gRadioPowerState, new_state);
    362   gRadioPowerState = new_state;
    363 
    364   if (new_state == RADIO_STATE_OFF) {
    365     TearDownNetworkInterface();
    366   }
    367 
    368   if (t != NULL) {
    369     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    370   }
    371 
    372   gce_ril_env->OnUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
    373                                      NULL, 0);
    374 
    375   pollSIMState(NULL);
    376 }
    377 
    378 // returns 1 if on, 0 if off, and -1 on error
    379 static void request_radio_power(void* data, size_t /*datalen*/, RIL_Token t) {
    380   int on = ((int*)data)[0];
    381   set_radio_state(on ? RADIO_STATE_ON : RADIO_STATE_OFF, t);
    382 }
    383 
    384 // TODO(ender): this should be a class member. Move where it belongs.
    385 struct CallState {
    386   RIL_CallState state;  // e.g. RIL_CALL_HOLDING;
    387   bool isInternational;
    388   bool isMobileTerminated;
    389   bool isVoice;
    390   bool isMultiParty;
    391 
    392   std::string number;
    393   std::string name;
    394   std::string dtmf;
    395 
    396   bool canPresentNumber;
    397   bool canPresentName;
    398 
    399   CallState()
    400       : state(RIL_CallState(0)),
    401         isInternational(false),
    402         isMobileTerminated(true),
    403         isVoice(true),
    404         isMultiParty(false),
    405         canPresentNumber(true),
    406         canPresentName(true) {}
    407 
    408   CallState(const std::string& number)
    409       : state(RIL_CALL_INCOMING),
    410         isInternational(false),
    411         isMobileTerminated(true),
    412         isVoice(true),
    413         isMultiParty(false),
    414         number(number),
    415         name(number),
    416         canPresentNumber(true),
    417         canPresentName(true) {}
    418 
    419   bool isBackground() { return state == RIL_CALL_HOLDING; }
    420 
    421   bool isActive() { return state == RIL_CALL_ACTIVE; }
    422 
    423   bool isDialing() { return state == RIL_CALL_DIALING; }
    424 
    425   bool isIncoming() { return state == RIL_CALL_INCOMING; }
    426 
    427   bool isWaiting() { return state == RIL_CALL_WAITING; }
    428 
    429   void addDtmfDigit(char c) {
    430     dtmf.push_back(c);
    431     ALOGV("Call to %s: DTMF %s", number.c_str(), dtmf.c_str());
    432   }
    433 
    434   bool makeBackground() {
    435     if (state == RIL_CALL_ACTIVE) {
    436       state = RIL_CALL_HOLDING;
    437       return true;
    438     }
    439 
    440     return false;
    441   }
    442 
    443   bool makeActive() {
    444     if (state == RIL_CALL_INCOMING || state == RIL_CALL_WAITING ||
    445         state == RIL_CALL_DIALING || state == RIL_CALL_HOLDING) {
    446       state = RIL_CALL_ACTIVE;
    447       return true;
    448     }
    449 
    450     return false;
    451   }
    452 };
    453 
    454 static int gLastActiveCallIndex = 1;
    455 static int gMicrophoneMute = 0;
    456 static std::map<int, CallState> gActiveCalls;
    457 
    458 static void request_get_current_calls(void* /*data*/, size_t /*datalen*/,
    459                                       RIL_Token t) {
    460   const int countCalls = gActiveCalls.size();
    461 
    462   RIL_Call** pp_calls = (RIL_Call**)alloca(countCalls * sizeof(RIL_Call*));
    463   RIL_Call* p_calls = (RIL_Call*)alloca(countCalls * sizeof(RIL_Call));
    464 
    465   memset(p_calls, 0, countCalls * sizeof(RIL_Call));
    466 
    467   /* init the pointer array */
    468   for (int i = 0; i < countCalls; i++) {
    469     pp_calls[i] = &(p_calls[i]);
    470   }
    471 
    472   // TODO(ender): This should be built from calls requested via RequestDial.
    473   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    474        iter != gActiveCalls.end(); ++iter, ++p_calls) {
    475     p_calls->state = iter->second.state;
    476     p_calls->index = iter->first;
    477     p_calls->toa = iter->second.isInternational ? 145 : 129;
    478     p_calls->isMpty = iter->second.isMultiParty;
    479     p_calls->isMT = iter->second.isMobileTerminated;
    480     p_calls->als = iter->first;
    481     p_calls->isVoice = iter->second.isVoice;
    482     p_calls->isVoicePrivacy = 0;
    483     p_calls->number = strdup(iter->second.number.c_str());
    484     p_calls->numberPresentation = iter->second.canPresentNumber ? 0 : 1;
    485     p_calls->name = strdup(iter->second.name.c_str());
    486     p_calls->namePresentation = iter->second.canPresentName ? 0 : 1;
    487     p_calls->uusInfo = NULL;
    488 
    489     ALOGV("Call to %s (%s): voice=%d mt=%d type=%d state=%d index=%d",
    490           p_calls->name, p_calls->number, p_calls->isVoice, p_calls->isMT,
    491           p_calls->toa, p_calls->state, p_calls->index);
    492   }
    493 
    494   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, pp_calls,
    495                                  countCalls * sizeof(RIL_Call*));
    496 
    497   ALOGV("Get Current calls: %d calls found.\n", countCalls);
    498 }
    499 
    500 static void simulate_pending_calls_answered(void* /*ignore*/) {
    501   ALOGV("Simulating outgoing call answered.");
    502   // This also resumes held calls.
    503   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    504        iter != gActiveCalls.end(); ++iter) {
    505     if (iter->second.isDialing()) {
    506       iter->second.makeActive();
    507     }
    508   }
    509 
    510   // Only unsolicited here.
    511   gce_ril_env->OnUnsolicitedResponse(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED,
    512                                      NULL, 0);
    513 }
    514 
    515 static void request_dial(void* data, size_t /*datalen*/, RIL_Token t) {
    516   RIL_Dial* p_dial = (RIL_Dial*)data;
    517 
    518   ALOGV("Dialing %s, number presentation is %s.", p_dial->address,
    519         (p_dial->clir == 0) ? "defined by operator"
    520                             : (p_dial->clir == 1) ? "allowed" : "restricted");
    521 
    522   CallState state(p_dial->address);
    523   state.isMobileTerminated = false;
    524   state.state = RIL_CALL_DIALING;
    525 
    526   switch (p_dial->clir) {
    527     case 0:  // default
    528     case 1:  // allow
    529       state.canPresentNumber = true;
    530       break;
    531 
    532     case 2:  // restrict
    533       state.canPresentNumber = false;
    534       break;
    535   }
    536 
    537   int call_index = gLastActiveCallIndex++;
    538   gActiveCalls[call_index] = state;
    539 
    540   static const struct timeval kAnswerTime = {5, 0};
    541   gce_ril_env->RequestTimedCallback(simulate_pending_calls_answered, NULL,
    542                                     &kAnswerTime);
    543 
    544   // success or failure is ignored by the upper layer here.
    545   // it will call GET_CURRENT_CALLS and determine success that way
    546   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    547 }
    548 
    549 void request_set_mute(void* data, size_t /*datalen*/, RIL_Token t) {
    550   gMicrophoneMute = ((int*)data)[0] != 0;
    551   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    552 }
    553 
    554 void request_get_mute(RIL_Token t) {
    555   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &gMicrophoneMute,
    556                                  sizeof(gMicrophoneMute));
    557 }
    558 
    559 // TODO(ender): this should be a class member. Move where it belongs.
    560 struct SmsMessage {
    561   enum SmsStatus { kUnread = 0, kRead = 1, kUnsent = 2, kSent = 3 };
    562 
    563   std::string message;
    564   SmsStatus status;
    565 };
    566 
    567 static int gNextMessageId = 1;
    568 static std::map<int, SmsMessage> gMessagesOnSimCard;
    569 
    570 static void request_write_sms_to_sim(void* data, size_t /*datalen*/,
    571                                      RIL_Token t) {
    572   RIL_SMS_WriteArgs* p_args = (RIL_SMS_WriteArgs*)data;
    573 
    574   SmsMessage message;
    575   message.status = SmsMessage::SmsStatus(p_args->status);
    576   message.message = p_args->pdu;
    577 
    578   ALOGV("Storing SMS message: '%s' with state: %s.", message.message.c_str(),
    579         (message.status < SmsMessage::kUnsent)
    580             ? ((message.status == SmsMessage::kRead) ? "READ" : "UNREAD")
    581             : ((message.status == SmsMessage::kSent) ? "SENT" : "UNSENT"));
    582 
    583   // TODO(ender): simulate SIM FULL?
    584   int index = gNextMessageId++;
    585   gMessagesOnSimCard[index] = message;
    586 
    587   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &index, sizeof(index));
    588 }
    589 
    590 static void request_delete_sms_on_sim(void* data, size_t /*datalen*/,
    591                                       RIL_Token t) {
    592   int index = *(int*)data;
    593 
    594   ALOGV("Delete SMS message %d", index);
    595 
    596   if (gMessagesOnSimCard.erase(index) == 0) {
    597     // No such message
    598     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
    599     return;
    600   }
    601 
    602   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    603 }
    604 
    605 static void request_hangup(void* data, size_t /*datalen*/, RIL_Token t) {
    606   int* p_line = (int*)data;
    607 
    608   ALOGV("Hanging up call %d.", *p_line);
    609   std::map<int, CallState>::iterator iter = gActiveCalls.find(*p_line);
    610 
    611   if (iter == gActiveCalls.end()) {
    612     ALOGV("No such call: %d.", *p_line);
    613     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
    614   } else {
    615     gActiveCalls.erase(iter);
    616     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    617   }
    618 }
    619 
    620 static void request_hangup_waiting(void* /*data*/, size_t /*datalen*/,
    621                                    RIL_Token t) {
    622   ALOGV("Hanging up background/held calls.");
    623   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    624        iter != gActiveCalls.end();) {
    625     if (iter->second.isBackground()) {
    626       // C++98 -- std::map::erase doesn't return iterator.
    627       std::map<int, CallState>::iterator temp = iter++;
    628       gActiveCalls.erase(temp);
    629     } else {
    630       ++iter;
    631     }
    632   }
    633   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    634 }
    635 
    636 static void request_hangup_current(RIL_Token t) {
    637   ALOGV("Hanging up foreground/active calls.");
    638   // This also resumes held calls.
    639   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    640        iter != gActiveCalls.end();) {
    641     if (iter->second.isBackground()) {
    642       iter->second.makeActive();
    643       ++iter;
    644     } else {
    645       // C++98 -- std::map::erase doesn't return iterator.
    646       std::map<int, CallState>::iterator temp = iter++;
    647       gActiveCalls.erase(temp);
    648     }
    649   }
    650   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    651 }
    652 
    653 static void request_switch_current_and_waiting(RIL_Token t) {
    654   ALOGV("Toggle foreground and background calls.");
    655   // TODO(ender): fix all states. Max 2 calls.
    656   //   BEFORE                               AFTER
    657   // Call 1   Call 2                 Call 1       Call 2
    658   // ACTIVE   HOLDING                HOLDING     ACTIVE
    659   // ACTIVE   WAITING                HOLDING     ACTIVE
    660   // HOLDING  WAITING                HOLDING     ACTIVE
    661   // ACTIVE   IDLE                   HOLDING     IDLE
    662   // IDLE     IDLE                   IDLE        IDLE
    663   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    664        iter != gActiveCalls.end(); ++iter) {
    665     // TODO(ender): call could also be waiting or dialing or...
    666     if (iter->second.isBackground()) {
    667       iter->second.makeActive();
    668     } else {
    669       iter->second.makeBackground();
    670     }
    671   }
    672   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    673 }
    674 
    675 static void request_answer_incoming(RIL_Token t) {
    676   ALOGV("Answering incoming call.");
    677 
    678   // There's two types of incoming calls:
    679   // - incoming: we are receiving this call while nothing happens,
    680   // - waiting: we are receiving this call while we're already talking.
    681   // We only accept the incoming ones.
    682   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    683        iter != gActiveCalls.end(); ++iter) {
    684     if (iter->second.isIncoming()) {
    685       iter->second.makeActive();
    686     }
    687   }
    688   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    689 }
    690 
    691 static void request_combine_multiparty_call(void* /*data*/, size_t /*datalen*/,
    692                                             RIL_Token t) {
    693   ALOGW("Conference calls are not supported.");
    694   gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
    695 }
    696 
    697 static void request_split_multiparty_call(void* /*data*/, size_t /*datalen*/,
    698                                           RIL_Token t) {
    699   ALOGW("Conference calls are not supported.");
    700   gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
    701 }
    702 
    703 static void request_udub_on_incoming_calls(RIL_Token t) {
    704   // UDUB = user determined user busy.
    705   // We don't exactly do that. We simply drop these calls.
    706   ALOGV("Reporting busy signal to incoming calls.");
    707   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    708        iter != gActiveCalls.end();) {
    709     // If we have an incoming call, there should be no waiting call.
    710     // If we have a waiting call, then previous incoming call has been answered.
    711     if (iter->second.isIncoming() || iter->second.isWaiting()) {
    712       // C++98 -- std::map::erase doesn't return iterator.
    713       std::map<int, CallState>::iterator temp = iter++;
    714       gActiveCalls.erase(temp);
    715     } else {
    716       ++iter;
    717     }
    718   }
    719   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    720 }
    721 
    722 static void request_send_dtmf(void* data, size_t /*datalen*/, RIL_Token t) {
    723   char c = ((char*)data)[0];
    724   ALOGV("Sending DTMF digit '%c'", c);
    725 
    726   for (std::map<int, CallState>::iterator iter = gActiveCalls.begin();
    727        iter != gActiveCalls.end(); ++iter) {
    728     if (iter->second.isActive()) {
    729       iter->second.addDtmfDigit(c);
    730       break;
    731     }
    732   }
    733 
    734   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    735 }
    736 
    737 static void request_send_dtmf_stop(RIL_Token t) {
    738   ALOGV("DTMF tone end.");
    739 
    740   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
    741 }
    742 
    743 // Check SignalStrength.java file for more details on how these map to signal
    744 // strength bars.
    745 const int kGatewaySignalStrengthMin = 4;
    746 const int kGatewaySignalStrengthMax = 30;
    747 const int kCDMASignalStrengthMin = -110;
    748 const int kCDMASignalStrengthMax = -60;
    749 const int kEVDOSignalStrengthMin = -160;
    750 const int kEVDOSignalStrengthMax = -70;
    751 const int kLTESignalStrengthMin = 4;
    752 const int kLTESignalStrengthMax = 30;
    753 
    754 static int gGatewaySignalStrength = kGatewaySignalStrengthMax;
    755 static int gCDMASignalStrength = kCDMASignalStrengthMax;
    756 static int gEVDOSignalStrength = kEVDOSignalStrengthMax;
    757 static int gLTESignalStrength = kLTESignalStrengthMax;
    758 
    759 static void request_signal_strength(void* /*data*/, size_t /*datalen*/,
    760                                     RIL_Token t) {
    761   // TODO(ender): possible to support newer APIs here.
    762 #if VSOC_PLATFORM_SDK_AFTER(N_MR1)
    763   RIL_SignalStrength_v10 strength;
    764 #else
    765   RIL_SignalStrength_v6 strength;
    766 #endif
    767 
    768   gGatewaySignalStrength += (rand() % 3 - 1);
    769   gCDMASignalStrength += (rand() % 3 - 1);
    770   gEVDOSignalStrength += (rand() % 3 - 1);
    771   gLTESignalStrength += (rand() % 3 - 1);
    772 
    773   if (gGatewaySignalStrength < kGatewaySignalStrengthMin)
    774     gGatewaySignalStrength = kGatewaySignalStrengthMin;
    775   if (gGatewaySignalStrength > kGatewaySignalStrengthMax)
    776     gGatewaySignalStrength = kGatewaySignalStrengthMax;
    777   if (gCDMASignalStrength < kCDMASignalStrengthMin)
    778     gCDMASignalStrength = kCDMASignalStrengthMin;
    779   if (gCDMASignalStrength > kCDMASignalStrengthMax)
    780     gCDMASignalStrength = kCDMASignalStrengthMax;
    781   if (gEVDOSignalStrength < kEVDOSignalStrengthMin)
    782     gEVDOSignalStrength = kEVDOSignalStrengthMin;
    783   if (gEVDOSignalStrength > kEVDOSignalStrengthMax)
    784     gEVDOSignalStrength = kEVDOSignalStrengthMax;
    785   if (gLTESignalStrength < kLTESignalStrengthMin)
    786     gLTESignalStrength = kLTESignalStrengthMin;
    787   if (gLTESignalStrength > kLTESignalStrengthMax)
    788     gLTESignalStrength = kLTESignalStrengthMax;
    789 
    790   strength.GW_SignalStrength.signalStrength = gGatewaySignalStrength;
    791   strength.GW_SignalStrength.bitErrorRate = 0;  // 0..7%
    792 
    793   strength.CDMA_SignalStrength.dbm = gCDMASignalStrength;
    794   strength.CDMA_SignalStrength.ecio = 0;  // Ec/Io; keep high to use dbm.
    795 
    796   strength.EVDO_SignalStrength.dbm = gEVDOSignalStrength;
    797   strength.EVDO_SignalStrength.ecio = 0;  // Ec/Io; keep high to use dbm.
    798 
    799   strength.LTE_SignalStrength.signalStrength = gLTESignalStrength;
    800   strength.LTE_SignalStrength.rsrp = INT_MAX;   // Invalid = Use signalStrength.
    801   strength.LTE_SignalStrength.rsrq = INT_MAX;   // Invalid = Use signalStrength.
    802   strength.LTE_SignalStrength.rssnr = INT_MAX;  // Invalid = Use signalStrength.
    803   strength.LTE_SignalStrength.cqi = INT_MAX;    // Invalid = Use signalStrength.
    804 
    805   ALOGV("Reporting signal strength: GW=%d CDMA=%d EVDO=%d LTE=%d",
    806         gGatewaySignalStrength, gCDMASignalStrength, gEVDOSignalStrength,
    807         gLTESignalStrength);
    808 
    809   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &strength, sizeof(strength));
    810 }
    811 
    812 static std::map<RIL_PreferredNetworkType, int> gModemSupportedNetworkTypes;
    813 
    814 static void init_modem_supported_network_types() {
    815   gModemSupportedNetworkTypes[PREF_NET_TYPE_GSM_WCDMA] = MDM_GSM | MDM_WCDMA;
    816   gModemSupportedNetworkTypes[PREF_NET_TYPE_GSM_ONLY] = MDM_GSM;
    817   gModemSupportedNetworkTypes[PREF_NET_TYPE_WCDMA] = MDM_WCDMA;
    818   gModemSupportedNetworkTypes[PREF_NET_TYPE_GSM_WCDMA_AUTO] =
    819       MDM_GSM | MDM_WCDMA;
    820   gModemSupportedNetworkTypes[PREF_NET_TYPE_CDMA_EVDO_AUTO] =
    821       MDM_CDMA | MDM_EVDO;
    822   gModemSupportedNetworkTypes[PREF_NET_TYPE_CDMA_ONLY] = MDM_CDMA;
    823   gModemSupportedNetworkTypes[PREF_NET_TYPE_EVDO_ONLY] = MDM_EVDO;
    824   gModemSupportedNetworkTypes[PREF_NET_TYPE_GSM_WCDMA_CDMA_EVDO_AUTO] =
    825       MDM_GSM | MDM_WCDMA | MDM_CDMA | MDM_EVDO;
    826   gModemSupportedNetworkTypes[PREF_NET_TYPE_LTE_CDMA_EVDO] =
    827       MDM_LTE | MDM_CDMA | MDM_EVDO;
    828   gModemSupportedNetworkTypes[PREF_NET_TYPE_LTE_GSM_WCDMA] =
    829       MDM_LTE | MDM_GSM | MDM_WCDMA;
    830   gModemSupportedNetworkTypes[PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA] =
    831       MDM_LTE | MDM_CDMA | MDM_EVDO | MDM_GSM | MDM_WCDMA;
    832   gModemSupportedNetworkTypes[PREF_NET_TYPE_LTE_ONLY] = MDM_LTE;
    833 }
    834 
    835 static std::map<RIL_PreferredNetworkType, int> gModemTechnologies;
    836 
    837 RIL_RadioTechnology gDataTechnologiesPreferenceOrder[] = {
    838     RADIO_TECH_LTE,    RADIO_TECH_EHRPD, RADIO_TECH_HSPAP,  RADIO_TECH_HSPA,
    839     RADIO_TECH_HSDPA,  RADIO_TECH_HSUPA, RADIO_TECH_EVDO_B, RADIO_TECH_EVDO_A,
    840     RADIO_TECH_EVDO_0, RADIO_TECH_1xRTT, RADIO_TECH_UMTS,   RADIO_TECH_EDGE,
    841     RADIO_TECH_GPRS};
    842 
    843 RIL_RadioTechnology gVoiceTechnologiesPreferenceOrder[] = {
    844     RADIO_TECH_LTE,    RADIO_TECH_EHRPD, RADIO_TECH_EVDO_B, RADIO_TECH_EVDO_A,
    845     RADIO_TECH_EVDO_0, RADIO_TECH_1xRTT, RADIO_TECH_IS95B,  RADIO_TECH_IS95A,
    846     RADIO_TECH_UMTS,   RADIO_TECH_GSM};
    847 
    848 static void init_modem_technologies() {
    849   gModemTechnologies[PREF_NET_TYPE_GSM_WCDMA] =
    850       (1 << RADIO_TECH_GSM) | (1 << RADIO_TECH_GPRS) | (1 << RADIO_TECH_EDGE) |
    851       (1 << RADIO_TECH_UMTS);
    852   gModemTechnologies[PREF_NET_TYPE_GSM_ONLY] =
    853       (1 << RADIO_TECH_GSM) | (1 << RADIO_TECH_GPRS) | (1 << RADIO_TECH_EDGE);
    854   gModemTechnologies[PREF_NET_TYPE_WCDMA] =
    855       (1 << RADIO_TECH_EDGE) | (1 << RADIO_TECH_UMTS);
    856   gModemTechnologies[PREF_NET_TYPE_GSM_WCDMA_AUTO] =
    857       (1 << RADIO_TECH_GSM) | (1 << RADIO_TECH_GPRS) | (1 << RADIO_TECH_EDGE) |
    858       (1 << RADIO_TECH_UMTS);
    859   gModemTechnologies[PREF_NET_TYPE_CDMA_EVDO_AUTO] =
    860       (1 << RADIO_TECH_IS95A) | (1 << RADIO_TECH_IS95B) |
    861       (1 << RADIO_TECH_1xRTT) | (1 << RADIO_TECH_EVDO_0) |
    862       (1 << RADIO_TECH_EVDO_A) | (1 << RADIO_TECH_HSDPA) |
    863       (1 << RADIO_TECH_HSUPA) | (1 << RADIO_TECH_HSPA) |
    864       (1 << RADIO_TECH_EVDO_B);
    865   gModemTechnologies[PREF_NET_TYPE_CDMA_ONLY] = (1 << RADIO_TECH_IS95A) |
    866                                                 (1 << RADIO_TECH_IS95B) |
    867                                                 (1 << RADIO_TECH_1xRTT);
    868   gModemTechnologies[PREF_NET_TYPE_EVDO_ONLY] =
    869       (1 << RADIO_TECH_EVDO_0) | (1 << RADIO_TECH_EVDO_A) |
    870       (1 << RADIO_TECH_EVDO_A) | (1 << RADIO_TECH_HSDPA) |
    871       (1 << RADIO_TECH_HSUPA) | (1 << RADIO_TECH_HSPA) |
    872       (1 << RADIO_TECH_EVDO_B);
    873   gModemTechnologies[PREF_NET_TYPE_GSM_WCDMA_CDMA_EVDO_AUTO] =
    874       (1 << RADIO_TECH_GSM) | (1 << RADIO_TECH_GPRS) | (1 << RADIO_TECH_EDGE) |
    875       (1 << RADIO_TECH_UMTS) | (1 << RADIO_TECH_IS95A) |
    876       (1 << RADIO_TECH_IS95B) | (1 << RADIO_TECH_1xRTT) |
    877       (1 << RADIO_TECH_EVDO_0) | (1 << RADIO_TECH_EVDO_A) |
    878       (1 << RADIO_TECH_HSDPA) | (1 << RADIO_TECH_HSUPA) |
    879       (1 << RADIO_TECH_HSPA) | (1 << RADIO_TECH_EVDO_B);
    880   gModemTechnologies[PREF_NET_TYPE_LTE_CDMA_EVDO] =
    881       (1 << RADIO_TECH_HSPAP) | (1 << RADIO_TECH_LTE) |
    882       (1 << RADIO_TECH_EHRPD) | (1 << RADIO_TECH_IS95A) |
    883       (1 << RADIO_TECH_IS95B) | (1 << RADIO_TECH_1xRTT) |
    884       (1 << RADIO_TECH_EVDO_0) | (1 << RADIO_TECH_EVDO_A) |
    885       (1 << RADIO_TECH_HSDPA) | (1 << RADIO_TECH_HSUPA) |
    886       (1 << RADIO_TECH_HSPA) | (1 << RADIO_TECH_EVDO_B);
    887   gModemTechnologies[PREF_NET_TYPE_LTE_GSM_WCDMA] =
    888       (1 << RADIO_TECH_HSPAP) | (1 << RADIO_TECH_LTE) |
    889       (1 << RADIO_TECH_EHRPD) | (1 << RADIO_TECH_GSM) | (1 << RADIO_TECH_GPRS) |
    890       (1 << RADIO_TECH_EDGE) | (1 << RADIO_TECH_UMTS);
    891 
    892   gModemTechnologies[PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA] =
    893       (1 << RADIO_TECH_HSPAP) | (1 << RADIO_TECH_LTE) |
    894       (1 << RADIO_TECH_EHRPD) | (1 << RADIO_TECH_IS95A) |
    895       (1 << RADIO_TECH_IS95B) | (1 << RADIO_TECH_1xRTT) |
    896       (1 << RADIO_TECH_EVDO_0) | (1 << RADIO_TECH_EVDO_A) |
    897       (1 << RADIO_TECH_HSDPA) | (1 << RADIO_TECH_HSUPA) |
    898       (1 << RADIO_TECH_HSPA) | (1 << RADIO_TECH_EVDO_B) |
    899       (1 << RADIO_TECH_GSM) | (1 << RADIO_TECH_GPRS) | (1 << RADIO_TECH_EDGE) |
    900       (1 << RADIO_TECH_UMTS);
    901   gModemTechnologies[PREF_NET_TYPE_LTE_ONLY] =
    902       (1 << RADIO_TECH_HSPAP) | (1 << RADIO_TECH_LTE) | (1 << RADIO_TECH_EHRPD);
    903 }
    904 
    905 static const RIL_PreferredNetworkType gModemDefaultType =
    906     PREF_NET_TYPE_LTE_GSM_WCDMA;
    907 static RIL_PreferredNetworkType gModemCurrentType = gModemDefaultType;
    908 static RIL_RadioTechnology gModemVoiceTechnology = RADIO_TECH_LTE;
    909 
    910 // Report technology change.
    911 // Select best technology from the list of supported techs.
    912 // Demotes RADIO_TECH_GSM as it's voice-only.
    913 static RIL_RadioTechnology getBestDataTechnology(
    914     RIL_PreferredNetworkType network_type) {
    915   RIL_RadioTechnology technology = RADIO_TECH_GPRS;
    916 
    917   std::map<RIL_PreferredNetworkType, int>::iterator iter =
    918       gModemTechnologies.find(network_type);
    919 
    920   ALOGV("Searching for best data technology for network type %d...",
    921         network_type);
    922 
    923   // Find which technology bits are lit. Pick the top most.
    924   for (size_t tech_index = 0;
    925        tech_index < sizeof(gDataTechnologiesPreferenceOrder) /
    926                         sizeof(gDataTechnologiesPreferenceOrder[0]);
    927        ++tech_index) {
    928     if (iter->second & (1 << gDataTechnologiesPreferenceOrder[tech_index])) {
    929       technology = gDataTechnologiesPreferenceOrder[tech_index];
    930       break;
    931     }
    932   }
    933 
    934   ALOGV("Best data technology: %d.", technology);
    935   return technology;
    936 }
    937 
    938 static RIL_RadioTechnology getBestVoiceTechnology(
    939     RIL_PreferredNetworkType network_type) {
    940   RIL_RadioTechnology technology = RADIO_TECH_GSM;
    941 
    942   std::map<RIL_PreferredNetworkType, int>::iterator iter =
    943       gModemTechnologies.find(network_type);
    944 
    945   ALOGV("Searching for best voice technology for network type %d...",
    946         network_type);
    947 
    948   // Find which technology bits are lit. Pick the top most.
    949   for (size_t tech_index = 0;
    950        tech_index < sizeof(gVoiceTechnologiesPreferenceOrder) /
    951                         sizeof(gVoiceTechnologiesPreferenceOrder[0]);
    952        ++tech_index) {
    953     if (iter->second & (1 << gVoiceTechnologiesPreferenceOrder[tech_index])) {
    954       technology = gVoiceTechnologiesPreferenceOrder[tech_index];
    955       break;
    956     }
    957   }
    958 
    959   ALOGV("Best voice technology: %d.", technology);
    960   return technology;
    961 }
    962 
    963 static void setRadioTechnology(RIL_PreferredNetworkType network_type) {
    964   RIL_RadioTechnology technology = getBestVoiceTechnology(network_type);
    965 
    966   if (technology != gModemVoiceTechnology) {
    967     gModemVoiceTechnology = technology;
    968     gce_ril_env->OnUnsolicitedResponse(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
    969                                        &gModemVoiceTechnology,
    970                                        sizeof(gModemVoiceTechnology));
    971   }
    972 }
    973 
    974 #if VSOC_PLATFORM_SDK_AFTER(L)
    975 static void request_get_radio_capability(RIL_Token t) {
    976   ALOGV("Requesting radio capability.");
    977   RIL_RadioCapability rc;
    978   rc.version = RIL_RADIO_CAPABILITY_VERSION;
    979   rc.session = 1;
    980   rc.phase = RC_PHASE_CONFIGURED;
    981   rc.rat = RAF_HSPAP;
    982   strncpy(rc.logicalModemUuid, "com.google.cvdgce1.modem", MAX_UUID_LENGTH);
    983   rc.status = RC_STATUS_SUCCESS;
    984   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &rc, sizeof(rc));
    985 }
    986 
    987 static void request_set_radio_capability(void* data, size_t datalen,
    988                                          RIL_Token t) {
    989   RIL_RadioCapability* rc = (RIL_RadioCapability*)data;
    990   ALOGV(
    991       "RadioCapability version %d session %d phase %d rat %d "
    992       "logicalModemUuid %s status %d",
    993       rc->version, rc->session, rc->phase, rc->rat, rc->logicalModemUuid,
    994       rc->status);
    995   // TODO(ender): do something about these numbers.
    996   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, rc, datalen);
    997 }
    998 #endif
    999 
   1000 static void request_set_preferred_network_type(int /*request*/, void* data,
   1001                                                size_t /*datalen*/,
   1002                                                RIL_Token t) {
   1003   RIL_PreferredNetworkType desired_type = *(RIL_PreferredNetworkType*)(data);
   1004 
   1005   // TODO(ender): telephony still believes this phone is GSM only.
   1006   ALOGV("Requesting modem technology change -> %d", desired_type);
   1007 
   1008   if (gModemSupportedNetworkTypes.find(desired_type) ==
   1009       gModemSupportedNetworkTypes.end()) {
   1010     desired_type = gModemSupportedNetworkTypes.begin()->first;
   1011   }
   1012 
   1013   if (gModemCurrentType == desired_type) {
   1014     ALOGV("Modem technology already set to %d.", desired_type);
   1015     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1016     return;
   1017   }
   1018 
   1019   int supported_technologies = gModemSupportedNetworkTypes[gModemDefaultType];
   1020   int desired_technologies = gModemSupportedNetworkTypes[desired_type];
   1021 
   1022   ALOGV("Requesting modem technology change %d -> %d", gModemCurrentType,
   1023         desired_type);
   1024 
   1025   // Check if we support this technology.
   1026   if ((supported_technologies & desired_technologies) != desired_technologies) {
   1027     ALOGV("Desired technology is not supported.");
   1028     gce_ril_env->OnRequestComplete(t, RIL_E_MODE_NOT_SUPPORTED, NULL, 0);
   1029     return;
   1030   }
   1031 
   1032   gModemCurrentType = desired_type;
   1033   setRadioTechnology(desired_type);
   1034   ALOGV("Technology change successful.");
   1035   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1036 }
   1037 
   1038 static void request_get_preferred_network_type(int /*request*/, void* /*data*/,
   1039                                                size_t /*datalen*/,
   1040                                                RIL_Token t) {
   1041   gce_ril_env->OnRequestComplete(
   1042       t, RIL_E_SUCCESS,
   1043       const_cast<RIL_PreferredNetworkType*>(&gModemDefaultType),
   1044       sizeof(gModemDefaultType));
   1045 }
   1046 
   1047 enum RegistrationState {
   1048   kUnregistered = 0,
   1049   kRegisteredInHomeNetwork = 1,
   1050   kSearchingForOperators = 2,
   1051   kRegistrationDenied = 3,
   1052   kUnknown = 4,
   1053   kRegisteredInRoamingMode = 5,
   1054 
   1055   kUnregistered_EmergencyCallsOnly = 10,
   1056   kSearchingForOperators_EmergencyCallsOnly = 12,
   1057   kRegistrationDenied_EmergencyCallsOnly = 13,
   1058   kUnknown_EmergencyCallsOnly = 14
   1059 };
   1060 
   1061 static const char kCdmaMobileDeviceNumber[] = "5551234567";
   1062 static const char kCdmaSID[] = "123";
   1063 static const char kCdmaNID[] = "65535";  // special: indicates free roaming.
   1064 
   1065 static void request_registration_state(int request, void* /*data*/,
   1066                                        size_t /*datalen*/, RIL_Token t) {
   1067   char** responseStr = NULL;
   1068   int numElements = 0;
   1069 
   1070   // See RIL_REQUEST_VOICE_REGISTRATION_STATE and
   1071   // RIL_REQUEST_DATA_REGISTRATION_STATE.
   1072   numElements = (request == RIL_REQUEST_VOICE_REGISTRATION_STATE) ? 15 : 6;
   1073   responseStr = (char**)malloc(numElements * sizeof(char*));
   1074 
   1075   asprintf(&responseStr[0], "%d", kRegisteredInHomeNetwork);
   1076   responseStr[1] = NULL;  // LAC - needed for GSM / WCDMA only.
   1077   responseStr[2] = NULL;  // CID - needed for GSM / WCDMA only.
   1078 
   1079   // This is (and always has been) a huge memory leak.
   1080   if (request == RIL_REQUEST_VOICE_REGISTRATION_STATE) {
   1081     ALOGV("Requesting voice registration state.");
   1082     asprintf(&responseStr[3], "%d", getBestVoiceTechnology(gModemCurrentType));
   1083     responseStr[4] = strdup("1");       // BSID
   1084     responseStr[5] = strdup("123");     // Latitude
   1085     responseStr[6] = strdup("222");     // Longitude
   1086     responseStr[7] = strdup("0");       // CSS Indicator
   1087     responseStr[8] = strdup(kCdmaSID);  // SID
   1088     responseStr[9] = strdup(kCdmaNID);  // NID
   1089     responseStr[10] = strdup("0");      // Roaming indicator
   1090     responseStr[11] = strdup("1");      // System is in PRL
   1091     responseStr[12] = strdup("0");      // Default Roaming indicator
   1092     responseStr[13] = strdup("0");      // Reason for denial
   1093     responseStr[14] = strdup("0");      // Primary Scrambling Code of Current
   1094   } else if (request == RIL_REQUEST_DATA_REGISTRATION_STATE) {
   1095     ALOGV("Requesting data registration state.");
   1096     asprintf(&responseStr[3], "%d", getBestDataTechnology(gModemCurrentType));
   1097     responseStr[4] = strdup("");   // DataServiceDenyReason
   1098     responseStr[5] = strdup("1");  // Max simultaneous data calls.
   1099   } else {
   1100     ALOGV("Unexpected request type: %d", request);
   1101     return;
   1102   }
   1103 
   1104   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, responseStr,
   1105                                  numElements * sizeof(responseStr));
   1106 }
   1107 
   1108 static void request_baseband_version(RIL_Token t) {
   1109   const char* response_str = "CVD_R1.0.0";
   1110 
   1111   ALOGV("Requested phone baseband version.");
   1112 
   1113   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, strdup(response_str),
   1114                                  sizeof(response_str));
   1115 }
   1116 
   1117 // Returns true, if modem is CDMA capable.
   1118 static bool isCDMA() {
   1119   switch (gModemCurrentType) {
   1120     case PREF_NET_TYPE_GSM_WCDMA:
   1121     case PREF_NET_TYPE_GSM_ONLY:
   1122     case PREF_NET_TYPE_WCDMA:
   1123     case PREF_NET_TYPE_GSM_WCDMA_AUTO:
   1124     case PREF_NET_TYPE_LTE_GSM_WCDMA:
   1125     case PREF_NET_TYPE_LTE_ONLY:
   1126       return false;
   1127 
   1128     case PREF_NET_TYPE_CDMA_EVDO_AUTO:
   1129     case PREF_NET_TYPE_CDMA_ONLY:
   1130     case PREF_NET_TYPE_EVDO_ONLY:
   1131     case PREF_NET_TYPE_LTE_CDMA_EVDO:
   1132     case PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA:
   1133     case PREF_NET_TYPE_GSM_WCDMA_CDMA_EVDO_AUTO:
   1134       return true;
   1135     default:
   1136       break;
   1137   }
   1138 
   1139   ALOGE("INVALID MODEM TYPE: %d", gModemCurrentType);
   1140   return false;
   1141 }
   1142 
   1143 // Returns true, if modem is GSM capable.
   1144 // Note, this is not same as !isCDMA().
   1145 static bool isGSM() {
   1146   switch (gModemCurrentType) {
   1147     case PREF_NET_TYPE_GSM_WCDMA:
   1148     case PREF_NET_TYPE_GSM_ONLY:
   1149     case PREF_NET_TYPE_WCDMA:
   1150     case PREF_NET_TYPE_GSM_WCDMA_AUTO:
   1151     case PREF_NET_TYPE_LTE_GSM_WCDMA:
   1152     case PREF_NET_TYPE_LTE_ONLY:
   1153     case PREF_NET_TYPE_GSM_WCDMA_CDMA_EVDO_AUTO:
   1154       return true;
   1155 
   1156     case PREF_NET_TYPE_CDMA_EVDO_AUTO:
   1157     case PREF_NET_TYPE_CDMA_ONLY:
   1158     case PREF_NET_TYPE_EVDO_ONLY:
   1159     case PREF_NET_TYPE_LTE_CDMA_EVDO:
   1160     case PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA:
   1161       return false;
   1162     default:
   1163       break;
   1164   }
   1165 
   1166   ALOGE("INVALID MODEM TYPE: %d", gModemCurrentType);
   1167   return false;
   1168 }
   1169 
   1170 static const char gIdentityGsmImei[] = "12345678902468";  // Luhn cksum = 0.
   1171 static const char gIdentityGsmImeiSv[] = "01";            // Arbitrary version.
   1172 static const char gIdentityCdmaEsn[] = "A0123456";        // 8 digits, ^[A-F].*
   1173 static const char gIdentityCdmaMeid[] =
   1174     "A0123456789012";  // 14 digits, ^[A-F].*
   1175 
   1176 static void request_get_imei(RIL_Token t) {
   1177   ALOGV("Requesting IMEI");
   1178   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS,
   1179                                  const_cast<char*>(gIdentityGsmImei),
   1180                                  strlen(gIdentityGsmImei));
   1181 }
   1182 
   1183 static void request_get_imei_sv(RIL_Token t) {
   1184   ALOGV("Requesting IMEI SV");
   1185   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS,
   1186                                  const_cast<char*>(gIdentityGsmImeiSv),
   1187                                  strlen(gIdentityGsmImeiSv));
   1188 }
   1189 
   1190 static void request_device_identity(int /*request*/, void* /*data*/,
   1191                                     size_t /*datalen*/, RIL_Token t) {
   1192   char* response[4] = {NULL};
   1193 
   1194   ALOGV("Requesting device identity...");
   1195 
   1196   if (isCDMA()) {
   1197     response[2] = strdup(&gIdentityCdmaEsn[0]);
   1198     response[3] = strdup(&gIdentityCdmaMeid[0]);
   1199   }
   1200 
   1201   if (isGSM()) {
   1202     response[0] = strdup(&gIdentityGsmImei[0]);
   1203     response[1] = strdup(&gIdentityGsmImeiSv[0]);
   1204   }
   1205 
   1206   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
   1207 
   1208   free(response[0]);
   1209   free(response[1]);
   1210 }
   1211 
   1212 // Let's pretend we have SIM for CDMA (by default).
   1213 static bool gCdmaHasSim = true;
   1214 static RIL_CdmaSubscriptionSource gCdmaSubscriptionType =
   1215     CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM;
   1216 
   1217 static void request_cdma_get_subscription_source(int /*request*/,
   1218                                                  void* /*data*/,
   1219                                                  size_t /*datalen*/,
   1220                                                  RIL_Token t) {
   1221   ALOGV("Requesting CDMA Subscription source.");
   1222 
   1223   if (!isCDMA()) {
   1224     // No such radio.
   1225     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1226     return;
   1227   }
   1228 
   1229   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &gCdmaSubscriptionType,
   1230                                  sizeof(gCdmaSubscriptionType));
   1231 }
   1232 
   1233 static void request_cdma_set_subscription_source(int /*request*/, void* data,
   1234                                                  size_t /*datalen*/,
   1235                                                  RIL_Token t) {
   1236   ALOGV("Setting CDMA Subscription source.");
   1237 
   1238   if (!isCDMA()) {
   1239     // No such radio.
   1240     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1241     return;
   1242   }
   1243 
   1244   RIL_CdmaSubscriptionSource new_source = *(RIL_CdmaSubscriptionSource*)(data);
   1245 
   1246   if (new_source == CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM && !gCdmaHasSim) {
   1247     // No such radio.
   1248     gce_ril_env->OnRequestComplete(t, RIL_E_SIM_ABSENT, NULL, 0);
   1249     return;
   1250   }
   1251 
   1252   ALOGV("Changed CDMA subscription type from %d to %d", gCdmaSubscriptionType,
   1253         new_source);
   1254   gCdmaSubscriptionType = new_source;
   1255 
   1256   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1257   gce_ril_env->OnUnsolicitedResponse(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
   1258                                      &gCdmaSubscriptionType,
   1259                                      sizeof(gCdmaSubscriptionType));
   1260 }
   1261 
   1262 static void request_cdma_subscription(int /*request*/, void* /*data*/,
   1263                                       size_t /*datalen*/, RIL_Token t) {
   1264   ALOGV("Requesting CDMA Subscription.");
   1265 
   1266   if (!isCDMA()) {
   1267     // No such radio.
   1268     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1269     return;
   1270   }
   1271 
   1272   char* responseStr[5] = {NULL};
   1273   responseStr[0] = strdup(&kCdmaMobileDeviceNumber[0]);  // MDN
   1274   responseStr[1] = strdup(&kCdmaSID[0]);                 // SID
   1275   responseStr[2] = strdup(&kCdmaNID[0]);                 // NID
   1276   responseStr[3] = strdup(&kCdmaMobileDeviceNumber[0]);  // MIN
   1277   responseStr[4] = strdup("1");                          // PRL Version
   1278   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, responseStr,
   1279                                  sizeof(responseStr));
   1280 }
   1281 
   1282 static const int gMaxConcurrentVoiceCalls = 4;
   1283 static const int gMaxConcurrentDataCalls = 4;
   1284 static const int gMaxConcurrentStandbyConnections = 4;
   1285 
   1286 #if VSOC_PLATFORM_SDK_AFTER(K)
   1287 static void request_hardware_config(RIL_Token t) {
   1288   RIL_HardwareConfig hw_cfg[2];
   1289 
   1290   ALOGV("Requesting hardware configuration.");
   1291 
   1292   strncpy(hw_cfg[0].uuid, "com.google.cvdgce1.modem", sizeof(hw_cfg[0].uuid));
   1293   strncpy(hw_cfg[1].uuid, "com.google.cvdgce1.sim", sizeof(hw_cfg[1].uuid));
   1294 
   1295   int technologies = 0;  // = unknown.
   1296   std::map<RIL_PreferredNetworkType, int>::iterator iter =
   1297       gModemTechnologies.find(gModemDefaultType);
   1298   if (iter != gModemTechnologies.end()) {
   1299     technologies = iter->second;
   1300   }
   1301 
   1302   hw_cfg[0].type = RIL_HARDWARE_CONFIG_MODEM;
   1303   hw_cfg[0].state = RIL_HARDWARE_CONFIG_STATE_ENABLED;
   1304   hw_cfg[0].cfg.modem.rilModel = 0;
   1305   hw_cfg[0].cfg.modem.rat = technologies;
   1306   hw_cfg[0].cfg.modem.maxVoice = gMaxConcurrentVoiceCalls;
   1307   hw_cfg[0].cfg.modem.maxData = gMaxConcurrentDataCalls;
   1308   hw_cfg[0].cfg.modem.maxStandby = gMaxConcurrentStandbyConnections;
   1309 
   1310   hw_cfg[1].type = RIL_HARDWARE_CONFIG_SIM;
   1311   hw_cfg[1].state = RIL_HARDWARE_CONFIG_STATE_ENABLED;
   1312   memcpy(hw_cfg[1].cfg.sim.modemUuid, hw_cfg[0].uuid,
   1313          sizeof(hw_cfg[1].cfg.sim.modemUuid));
   1314 
   1315   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &hw_cfg, sizeof(hw_cfg));
   1316 }
   1317 #endif
   1318 
   1319 // 0 = Home network only, 1 = preferred networks only, 2 = all networks.
   1320 static int gCdmaRoamingPreference = 2;
   1321 
   1322 static void request_cdma_get_roaming_preference(int /*request*/, void* /*data*/,
   1323                                                 size_t /*datalen*/,
   1324                                                 RIL_Token t) {
   1325   if (!isCDMA()) {
   1326     // No such radio.
   1327     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1328     return;
   1329   }
   1330 
   1331   ALOGV("Requesting CDMA Roaming preference");
   1332 
   1333   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &gCdmaRoamingPreference,
   1334                                  sizeof(gCdmaRoamingPreference));
   1335 }
   1336 
   1337 static void request_cdma_set_roaming_preference(int /*request*/, void* data,
   1338                                                 size_t /*datalen*/,
   1339                                                 RIL_Token t) {
   1340   if (!isCDMA()) {
   1341     // No such radio.
   1342     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1343     return;
   1344   }
   1345 
   1346   int pref = *(int*)data;
   1347   ALOGV("Changing CDMA roaming preference: %d -> %d", gCdmaRoamingPreference,
   1348         pref);
   1349 
   1350   if ((pref < 0) || (pref > 2)) {
   1351     ALOGV("Unsupported roaming preference: %d", pref);
   1352     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   1353     return;
   1354   }
   1355 
   1356   gCdmaRoamingPreference = pref;
   1357   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1358 }
   1359 
   1360 static void request_send_ussd(void* /*data*/, size_t /*datalen*/, RIL_Token t) {
   1361   ALOGV("Sending USSD code is currently not supported");
   1362   // TODO(ender): support this feature
   1363   gce_ril_env->OnRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
   1364 }
   1365 
   1366 static void request_cancel_ussd(RIL_Token t) {
   1367   ALOGV("Cancelling USSD code is currently not supported");
   1368   // TODO(ender): support this feature
   1369   gce_ril_env->OnRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
   1370 }
   1371 
   1372 static void request_exit_emergency_mode(void* /*data*/, size_t /*datalen*/,
   1373                                         RIL_Token t) {
   1374   ALOGV("Exiting emergency callback mode.");
   1375 
   1376   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1377 }
   1378 
   1379 static RIL_RadioState gce_ril_current_state() {
   1380   ALOGV("Reporting radio state %d", gRadioPowerState);
   1381   return gRadioPowerState;
   1382 }
   1383 
   1384 static int gce_ril_on_supports(int requestCode) {
   1385   ALOGE("%s: Request code %d not implemented", __FUNCTION__, requestCode);
   1386   return 1;
   1387 }
   1388 
   1389 static void gce_ril_on_cancel(RIL_Token /*t*/) {
   1390   ALOGE("Cancel operation not implemented");
   1391 }
   1392 
   1393 static const char* gce_ril_get_version(void) {
   1394   ALOGV("Reporting VSOC version " VSOC_RIL_VERSION_STRING);
   1395   return VSOC_RIL_VERSION_STRING;
   1396 }
   1397 
   1398 static int s_cell_info_rate_ms = INT_MAX;
   1399 static int s_mcc = 0;
   1400 static int s_mnc = 0;
   1401 static int s_lac = 0;
   1402 static int s_cid = 0;
   1403 
   1404 std::vector<RIL_NeighboringCell> gGSMNeighboringCells;
   1405 
   1406 static void request_get_neighboring_cell_ids(void* /*data*/, size_t /*datalen*/,
   1407                                              RIL_Token t) {
   1408   ALOGV("Requesting GSM neighboring cell ids");
   1409 
   1410   if (!isGSM() || gGSMNeighboringCells.empty()) {
   1411     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   1412     return;
   1413   }
   1414 
   1415   RIL_NeighboringCell** cells =
   1416       new RIL_NeighboringCell*[gGSMNeighboringCells.size()];
   1417 
   1418   for (size_t index = 0; index < gGSMNeighboringCells.size(); ++index) {
   1419     cells[index] = &gGSMNeighboringCells[index];
   1420   }
   1421 
   1422   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, cells,
   1423                                  sizeof(RIL_NeighboringCell*));
   1424   delete[] cells;
   1425 }
   1426 
   1427 #if VSOC_PLATFORM_SDK_AFTER(J_MR1)
   1428 static void request_get_cell_info_list(void* /*data*/, size_t /*datalen*/,
   1429                                        RIL_Token t) {
   1430   struct timespec now;
   1431   uint64_t curTime;
   1432 
   1433   ALOGV("Requesting Cell Info List");
   1434 
   1435   clock_gettime(CLOCK_MONOTONIC, &now);
   1436   curTime = now.tv_sec * 1000000000LL + now.tv_nsec;
   1437 
   1438 #if VSOC_PLATFORM_SDK_AFTER(N_MR1)
   1439   RIL_CellInfo_v12 ci;
   1440 #else
   1441   RIL_CellInfo ci;
   1442 #endif
   1443 
   1444   if (isGSM()) {
   1445     ci.cellInfoType = RIL_CELL_INFO_TYPE_GSM;
   1446     ci.registered = 1;
   1447     ci.timeStampType = RIL_TIMESTAMP_TYPE_ANTENNA;  // Our own timestamp.
   1448     ci.timeStamp = curTime - 1000;                  // Fake time in the past.
   1449     ci.CellInfo.gsm.cellIdentityGsm.mcc = s_mcc;
   1450     ci.CellInfo.gsm.cellIdentityGsm.mnc = s_mnc;
   1451     ci.CellInfo.gsm.cellIdentityGsm.lac = s_lac;
   1452     ci.CellInfo.gsm.cellIdentityGsm.cid = s_cid;
   1453     ci.CellInfo.gsm.signalStrengthGsm.signalStrength = 10;
   1454     ci.CellInfo.gsm.signalStrengthGsm.bitErrorRate = 0;
   1455 
   1456     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &ci, sizeof(ci));
   1457   } else if (isCDMA()) {
   1458     // TODO(ender): CDMA cell support. And LTE.
   1459     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1460   } else {
   1461     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   1462   }
   1463 }
   1464 #endif
   1465 
   1466 struct NetworkOperator {
   1467   std::string long_name;
   1468   std::string short_name;
   1469   bool is_accessible;
   1470 
   1471   NetworkOperator() {}
   1472 
   1473   NetworkOperator(const std::string& long_name, const std::string& short_name,
   1474                   bool is_accessible)
   1475       : long_name(long_name),
   1476         short_name(short_name),
   1477         is_accessible(is_accessible) {}
   1478 };
   1479 
   1480 static std::map<std::string, NetworkOperator> gNetworkOperators;
   1481 static std::string gCurrentNetworkOperator = "";
   1482 
   1483 enum OperatorSelectionMethod {
   1484   kOperatorAutomatic = 0,
   1485   kOperatorManual = 1,
   1486   kOperatorDeregistered = 2,
   1487   kOperatorManualThenAutomatic = 4
   1488 };
   1489 
   1490 static void init_virtual_network() {
   1491   gGSMNeighboringCells.resize(1);
   1492   gGSMNeighboringCells[0].cid = (char*)"0000";
   1493   gGSMNeighboringCells[0].rssi = 75;
   1494 #if VSOC_PLATFORM_SDK_AFTER(O_MR1)
   1495   gNetworkOperators["302780"] =
   1496 #else
   1497   gNetworkOperators["310260"] =
   1498 #endif
   1499       NetworkOperator("Android Virtual Operator", "Android", true);
   1500   gNetworkOperators["310300"] =
   1501       NetworkOperator("Alternative Operator", "Alternative", true);
   1502   gNetworkOperators["310400"] =
   1503       NetworkOperator("Hermetic Network Operator", "Hermetic", false);
   1504 }
   1505 
   1506 static OperatorSelectionMethod gOperatorSelectionMethod = kOperatorDeregistered;
   1507 
   1508 static void request_query_network_selection_mode(void* /*data*/,
   1509                                                  size_t /*datalen*/,
   1510                                                  RIL_Token t) {
   1511   ALOGV("Query operator selection mode (%d)", gOperatorSelectionMethod);
   1512   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &gOperatorSelectionMethod,
   1513                                  sizeof(gOperatorSelectionMethod));
   1514 }
   1515 
   1516 static void request_operator(void* /*data*/, size_t /*datalen*/, RIL_Token t) {
   1517   std::map<std::string, NetworkOperator>::iterator iter =
   1518       gNetworkOperators.find(gCurrentNetworkOperator);
   1519 
   1520   ALOGV("Requesting current operator info");
   1521 
   1522   if (iter == gNetworkOperators.end()) {
   1523     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   1524     return;
   1525   }
   1526 
   1527   const char* response[] = {iter->second.long_name.c_str(),
   1528                             iter->second.short_name.c_str(),
   1529                             iter->first.c_str()};
   1530 
   1531   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, response, sizeof(response));
   1532 }
   1533 
   1534 static void request_query_available_networks(void* /*data*/, size_t /*datalen*/,
   1535                                              RIL_Token t) {
   1536   const char** available_networks =
   1537       new const char*[gNetworkOperators.size() * 4];
   1538 
   1539   ALOGV("Querying available networks.");
   1540 
   1541   // TODO(ender): this should only respond once operator is selected and
   1542   // registered.
   1543   int index = 0;
   1544   for (std::map<std::string, NetworkOperator>::iterator iter =
   1545            gNetworkOperators.begin();
   1546        iter != gNetworkOperators.end(); ++iter) {
   1547     // TODO(ender): wrap in a neat structure maybe?
   1548     available_networks[index++] = iter->second.long_name.c_str();
   1549     available_networks[index++] = iter->second.short_name.c_str();
   1550     available_networks[index++] = iter->first.c_str();
   1551     if (!iter->second.is_accessible) {
   1552       available_networks[index++] = "forbidden";
   1553     } else if (iter->first == gCurrentNetworkOperator) {
   1554       available_networks[index++] = "current";
   1555     } else {
   1556       available_networks[index++] = "available";
   1557     }
   1558   }
   1559 
   1560   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &available_networks,
   1561                                  4 * gNetworkOperators.size());
   1562   delete[] available_networks;
   1563 }
   1564 
   1565 static void request_set_automatic_network_selection(RIL_Token t) {
   1566   ALOGV("Requesting automatic operator selection");
   1567   gCurrentNetworkOperator = gNetworkOperators.begin()->first;
   1568   gOperatorSelectionMethod = kOperatorAutomatic;
   1569   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1570 }
   1571 
   1572 static void request_set_manual_network_selection(void* data, size_t /*datalen*/,
   1573                                                  RIL_Token t) {
   1574   char* mccmnc = (char*)data;
   1575 
   1576   ALOGV("Requesting manual operator selection: %s", mccmnc);
   1577 
   1578   std::map<std::string, NetworkOperator>::iterator iter =
   1579       gNetworkOperators.find(mccmnc);
   1580 
   1581   if (iter == gNetworkOperators.end() || iter->second.is_accessible) {
   1582     gce_ril_env->OnRequestComplete(t, RIL_E_ILLEGAL_SIM_OR_ME, NULL, 0);
   1583     return;
   1584   }
   1585 
   1586   gCurrentNetworkOperator = mccmnc;
   1587   gOperatorSelectionMethod = kOperatorManual;
   1588 
   1589   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1590 }
   1591 
   1592 static const char kDefaultSMSC[] = "00";
   1593 static int gNextSmsMessageId = 1;
   1594 
   1595 static void request_cdma_send_SMS(void* /*data*/, RIL_Token t) {
   1596   RIL_SMS_Response response = {0, 0, 0};
   1597   // RIL_CDMA_SMS_Message* rcsm = (RIL_CDMA_SMS_Message*) data;
   1598 
   1599   ALOGW("CDMA SMS Send is currently not implemented.");
   1600 
   1601   // Cdma Send SMS implementation will go here:
   1602   // But it is not implemented yet.
   1603   memset(&response, 0, sizeof(response));
   1604   response.messageRef = -1;  // This must be BearerData MessageId.
   1605   gce_ril_env->OnRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response,
   1606                                  sizeof(response));
   1607 }
   1608 
   1609 static void request_send_SMS(void* data, RIL_Token t) {
   1610   RIL_SMS_Response response = {0, 0, 0};
   1611 
   1612   ALOGV("Send GSM SMS Message");
   1613 
   1614   // SMSC is an address of SMS center or NULL for default.
   1615   const char* smsc = ((const char**)data)[0];
   1616   if (smsc == NULL) smsc = &kDefaultSMSC[0];
   1617 
   1618   response.messageRef = gNextSmsMessageId++;
   1619   response.ackPDU = NULL;
   1620   response.errorCode = 0;
   1621 
   1622   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
   1623 
   1624   // response.messageRef = -1;
   1625   // gce_ril_env->OnRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response,
   1626   //                                sizeof(response));
   1627 }
   1628 
   1629 #if VSOC_PLATFORM_SDK_AFTER(J_MR1)
   1630 static void request_set_cell_info_list_rate(void* data, size_t /*datalen*/,
   1631                                             RIL_Token t) {
   1632   // For now we'll save the rate but no RIL_UNSOL_CELL_INFO_LIST messages
   1633   // will be sent.
   1634   ALOGV("Setting cell info list rate.");
   1635   s_cell_info_rate_ms = ((int*)data)[0];
   1636   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1637 }
   1638 #endif
   1639 #if VSOC_PLATFORM_SDK_AFTER(J_MR2)
   1640 static void request_ims_send_SMS(void* data, size_t /*datalen*/, RIL_Token t) {
   1641   RIL_IMS_SMS_Message* args = (RIL_IMS_SMS_Message*)data;
   1642   RIL_SMS_Response response{};
   1643 
   1644   ALOGV("Send IMS SMS Message");
   1645 
   1646   switch (args->tech) {
   1647     case RADIO_TECH_3GPP:
   1648       return request_send_SMS(args->message.gsmMessage, t);
   1649 
   1650     case RADIO_TECH_3GPP2:
   1651       return request_cdma_send_SMS(args->message.gsmMessage, t);
   1652 
   1653     default:
   1654       ALOGE("Invalid SMS format value: %d", args->tech);
   1655       response.messageRef = -2;
   1656       gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, &response,
   1657                                      sizeof(response));
   1658   }
   1659 }
   1660 #endif
   1661 
   1662 static void request_SMS_acknowledge(void* data, size_t /*datalen*/,
   1663                                     RIL_Token t) {
   1664   int* ack = (int*)data;
   1665 
   1666   // TODO(ender): we should retain "incoming" sms for later reception.
   1667   ALOGV("SMS receipt %ssuccessful (reason %d).", ack[0] ? "" : "un", ack[1]);
   1668 
   1669   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   1670 }
   1671 
   1672 struct SimFileCommand {
   1673   uint8_t command;
   1674   uint16_t efid;
   1675   uint8_t param1;
   1676   uint8_t param2;
   1677   uint8_t param3;
   1678 
   1679   bool operator<(const SimFileCommand& other) const {
   1680     uint64_t sum1, sum2;
   1681     sum1 = (command * 1ull << 40) | (efid * 1ull << 24) | (param1 << 16) |
   1682            (param2 << 8) | (param3);
   1683     sum2 = (other.command * 1ull << 40) | (other.efid * 1ull << 24) |
   1684            (other.param1 << 16) | (other.param2 << 8) | (other.param3);
   1685     return sum1 < sum2;
   1686   }
   1687 
   1688   SimFileCommand(uint8_t cmd, uint16_t efid, uint8_t p1, uint8_t p2, uint8_t p3)
   1689       : command(cmd), efid(efid), param1(p1), param2(p2), param3(p3) {}
   1690 };
   1691 
   1692 struct SimFileResponse {
   1693   uint8_t sw1;
   1694   uint8_t sw2;
   1695   const char* data;
   1696 
   1697   SimFileResponse() : sw1(0), sw2(0), data(NULL) {}
   1698 
   1699   SimFileResponse(uint8_t sw1, uint8_t sw2, const char* data)
   1700       : sw1(sw1), sw2(sw2), data(data) {}
   1701 };
   1702 
   1703 // TODO(ender): Double check & rewrite these.
   1704 std::map<SimFileCommand, SimFileResponse> gSimFileSystem;
   1705 
   1706 static void init_sim_file_system() {
   1707   gSimFileSystem[SimFileCommand(192, 28436, 0, 0, 15)] =
   1708       SimFileResponse(144, 0, "000000146f1404001aa0aa01020000");
   1709   gSimFileSystem[SimFileCommand(176, 28436, 0, 0, 20)] =
   1710       SimFileResponse(144, 0, "416e64726f6964ffffffffffffffffffffffffff");
   1711   gSimFileSystem[SimFileCommand(192, 28433, 0, 0, 15)] =
   1712       SimFileResponse(144, 0, "000000016f11040011a0aa01020000");
   1713   gSimFileSystem[SimFileCommand(176, 28433, 0, 0, 1)] =
   1714       SimFileResponse(144, 0, "55");
   1715   gSimFileSystem[SimFileCommand(192, 12258, 0, 0, 15)] =
   1716       SimFileResponse(144, 0, "0000000a2fe204000fa0aa01020000");
   1717   gSimFileSystem[SimFileCommand(176, 12258, 0, 0, 10)] =
   1718       SimFileResponse(144, 0, "98101430121181157002");
   1719   gSimFileSystem[SimFileCommand(192, 28435, 0, 0, 15)] =
   1720       SimFileResponse(144, 0, "000000016f13040011a0aa01020000");
   1721   gSimFileSystem[SimFileCommand(176, 28435, 0, 0, 1)] =
   1722       SimFileResponse(144, 0, "55");
   1723   gSimFileSystem[SimFileCommand(192, 28472, 0, 0, 15)] =
   1724       SimFileResponse(144, 0, "0000000f6f3804001aa0aa01020000");
   1725   gSimFileSystem[SimFileCommand(176, 28472, 0, 0, 15)] =
   1726       SimFileResponse(144, 0, "ff30ffff3c003c03000c0000f03f00");
   1727   gSimFileSystem[SimFileCommand(192, 28617, 0, 0, 15)] =
   1728       SimFileResponse(144, 0, "000000086fc9040011a0aa01020104");
   1729   gSimFileSystem[SimFileCommand(178, 28617, 1, 4, 4)] =
   1730       SimFileResponse(144, 0, "01000000");
   1731   gSimFileSystem[SimFileCommand(192, 28618, 0, 0, 15)] =
   1732       SimFileResponse(144, 0, "0000000a6fca040011a0aa01020105");
   1733   gSimFileSystem[SimFileCommand(178, 28618, 1, 4, 5)] =
   1734       SimFileResponse(144, 0, "0000000000");
   1735   gSimFileSystem[SimFileCommand(192, 28589, 0, 0, 15)] =
   1736       SimFileResponse(144, 0, "000000046fad04000aa0aa01020000");
   1737   gSimFileSystem[SimFileCommand(176, 28589, 0, 0, 4)] =
   1738       SimFileResponse(144, 0, "00000003");
   1739   gSimFileSystem[SimFileCommand(192, 28438, 0, 0, 15)] =
   1740       SimFileResponse(144, 0, "000000026f1604001aa0aa01020000");
   1741   gSimFileSystem[SimFileCommand(176, 28438, 0, 0, 2)] =
   1742       SimFileResponse(144, 0, "0233");
   1743   gSimFileSystem[SimFileCommand(192, 28486, 0, 0, 15)] =
   1744       SimFileResponse(148, 4, NULL);
   1745   gSimFileSystem[SimFileCommand(192, 28621, 0, 0, 15)] =
   1746       SimFileResponse(148, 4, NULL);
   1747   gSimFileSystem[SimFileCommand(192, 28613, 0, 0, 15)] =
   1748       SimFileResponse(144, 0, "000000f06fc504000aa0aa01020118");
   1749   gSimFileSystem[SimFileCommand(178, 28613, 1, 4, 24)] = SimFileResponse(
   1750       144, 0, "43058441aa890affffffffffffffffffffffffffffffffff");
   1751   gSimFileSystem[SimFileCommand(192, 28480, 0, 0, 15)] =
   1752       SimFileResponse(144, 0, "000000806f40040011a0aa01020120");
   1753   // Primary phone number encapsulated
   1754   // [51][55][21][43][65][f7] = 1 555 1234 567$
   1755   gSimFileSystem[SimFileCommand(178, 28480, 1, 4, 32)] = SimFileResponse(
   1756       144, 0,
   1757       "ffffffffffffffffffffffffffffffffffff07915155214365f7ffffffffffff");
   1758   gSimFileSystem[SimFileCommand(192, 28615, 0, 0, 15)] =
   1759       SimFileResponse(144, 0, "000000406fc7040011a0aa01020120");
   1760   // Voice mail number encapsulated
   1761   // [56][6f][69][63][65][6d][61][69][6c] = 'Voicemail'
   1762   // [51][55][67][45][23][f1] = 1 555 7654 321$
   1763   gSimFileSystem[SimFileCommand(178, 28615, 1, 4, 32)] = SimFileResponse(
   1764       144, 0,
   1765       "566f6963656d61696cffffffffffffffffff07915155674523f1ffffffffffff");
   1766   gSimFileSystem[SimFileCommand(192, 12037, 0, 0, 15)] =
   1767       SimFileResponse(148, 4, NULL);
   1768   gSimFileSystem[SimFileCommand(192, 28437, 0, 0, 15)] =
   1769       SimFileResponse(148, 4, NULL);
   1770   gSimFileSystem[SimFileCommand(192, 28478, 0, 0, 15)] =
   1771       SimFileResponse(148, 4, NULL);
   1772   gSimFileSystem[SimFileCommand(192, 28450, 0, 0, 15)] =
   1773       SimFileResponse(148, 4, NULL);
   1774   gSimFileSystem[SimFileCommand(192, 28456, 0, 0, 15)] =
   1775       SimFileResponse(148, 4, NULL);
   1776   gSimFileSystem[SimFileCommand(192, 28474, 0, 0, 15)] =
   1777       SimFileResponse(148, 4, NULL);
   1778   gSimFileSystem[SimFileCommand(192, 28481, 0, 0, 15)] =
   1779       SimFileResponse(148, 4, NULL);
   1780   gSimFileSystem[SimFileCommand(192, 28484, 0, 0, 15)] =
   1781       SimFileResponse(148, 4, NULL);
   1782   gSimFileSystem[SimFileCommand(192, 28493, 0, 0, 15)] =
   1783       SimFileResponse(148, 4, NULL);
   1784   gSimFileSystem[SimFileCommand(192, 28619, 0, 0, 15)] =
   1785       SimFileResponse(148, 4, NULL);
   1786   gSimFileSystem[SimFileCommand(176, 28506, 0, 0, 4)] =
   1787       SimFileResponse(144, 0, "00000013");
   1788 }
   1789 
   1790 static void request_SIM_IO(void* data, size_t /*datalen*/, RIL_Token t) {
   1791   const RIL_SIM_IO_v6& args = *(RIL_SIM_IO_v6*)data;
   1792   RIL_SIM_IO_Response sr = {0, 0, 0};
   1793 
   1794   ALOGV(
   1795       "Requesting SIM File IO: %d EFID %x, Params: %d, %d, %d, path: %s, "
   1796       "data %s PIN: %s AID: %s",
   1797       args.command, args.fileid, args.p1, args.p2, args.p3, args.path,
   1798       args.data, args.pin2, args.aidPtr);
   1799 
   1800   SimFileCommand cmd(args.command, args.fileid, args.p1, args.p2, args.p3);
   1801 
   1802   std::map<SimFileCommand, SimFileResponse>::iterator resp =
   1803       gSimFileSystem.find(cmd);
   1804 
   1805   if (resp != gSimFileSystem.end()) {
   1806     sr.sw1 = resp->second.sw1;
   1807     sr.sw2 = resp->second.sw2;
   1808     if (resp->second.data) sr.simResponse = strdup(resp->second.data);
   1809     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
   1810     return;
   1811   }
   1812 
   1813   ALOGW("Unsupported SIM File IO command.");
   1814   gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   1815 }
   1816 
   1817 static void request_enter_sim_pin(void* data, size_t /*datalen*/, RIL_Token t) {
   1818   const char** pin_aid = (const char**)data;
   1819 
   1820   ALOGV("Entering PIN: %s / %s", pin_aid[0], pin_aid[1]);
   1821 
   1822   ++gSimPINAttempts;
   1823   int remaining_attempts = gSimPINAttemptsMax - gSimPINAttempts;
   1824 
   1825   bool is_valid = false;
   1826 
   1827   if (gSimStatus == SIM_PIN) {
   1828     is_valid = (gSimPIN == pin_aid[0]);
   1829   } else if (gSimStatus == SIM_PUK) {
   1830     is_valid = (gSimPUK == pin_aid[0]);
   1831   } else {
   1832     ALOGV("Unexpected SIM status for unlock: %d", gSimStatus);
   1833     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   1834     return;
   1835   }
   1836 
   1837   if (!is_valid) {
   1838     if (gSimPINAttempts == gSimPINAttemptsMax) {
   1839       if (gSimStatus == SIM_PIN) {
   1840         gSimStatus = SIM_PUK;
   1841         gSimPINAttempts = 0;
   1842       } else {
   1843         ALOGV("PIN and PUK verification failed; locking SIM card.");
   1844         gSimStatus = SIM_NOT_READY;
   1845         gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   1846         return;
   1847       }
   1848     }
   1849 
   1850     gce_ril_env->OnRequestComplete(t, RIL_E_PASSWORD_INCORRECT,
   1851                                    &remaining_attempts,
   1852                                    sizeof(remaining_attempts));
   1853   } else {
   1854     if (gSimStatus == SIM_PUK) {
   1855       ALOGV("Resetting SIM PIN to %s", pin_aid[1]);
   1856       gSimPIN = pin_aid[1];
   1857     }
   1858 
   1859     gSimPINAttempts = 0;
   1860     gSimStatus = SIM_READY;
   1861     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &remaining_attempts,
   1862                                    sizeof(remaining_attempts));
   1863   }
   1864 
   1865   pollSIMState(NULL);
   1866 }
   1867 
   1868 /**
   1869  * No longer POLL.
   1870  */
   1871 static void pollSIMState(void* /*param*/) {
   1872   // TODO(ender): check radio state?
   1873 
   1874   ALOGV("Polling SIM Status.");
   1875 
   1876   switch (gSimStatus) {
   1877     case SIM_ABSENT:
   1878     case SIM_PIN:
   1879     case SIM_PUK:
   1880     case SIM_NETWORK_PERSONALIZATION:
   1881     default:
   1882       ALOGV("SIM Absent or Locked");
   1883       break;
   1884 
   1885     case SIM_NOT_READY:
   1886       // Transition directly to READY. Set default network operator.
   1887       if (gRadioPowerState == RADIO_STATE_ON) {
   1888         gSimStatus = SIM_READY;
   1889 #if VSOC_PLATFORM_SDK_AFTER(O_MR1)
   1890         gCurrentNetworkOperator = "302780";
   1891 #else
   1892         gCurrentNetworkOperator = "310260";
   1893 #endif
   1894       }
   1895 
   1896       gce_ril_env->RequestTimedCallback(pollSIMState, NULL, &TIMEVAL_SIMPOLL);
   1897       break;
   1898 
   1899     case SIM_READY:
   1900       ALOGV("SIM Ready. Notifying network state changed.");
   1901       break;
   1902   }
   1903 
   1904   if (gRadioPowerState != RADIO_STATE_OFF) {
   1905     gce_ril_env->OnUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED,
   1906                                        NULL, 0);
   1907     gce_ril_env->OnUnsolicitedResponse(
   1908         RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED, NULL, 0);
   1909   }
   1910 }
   1911 
   1912 std::map<SIM_Status, RIL_AppStatus> gRilAppStatus;
   1913 
   1914 static void init_sim_status() {
   1915   gRilAppStatus[SIM_ABSENT] = (RIL_AppStatus){RIL_APPTYPE_UNKNOWN,
   1916                                               RIL_APPSTATE_UNKNOWN,
   1917                                               RIL_PERSOSUBSTATE_UNKNOWN,
   1918                                               NULL,
   1919                                               NULL,
   1920                                               0,
   1921                                               RIL_PINSTATE_UNKNOWN,
   1922                                               RIL_PINSTATE_UNKNOWN};
   1923   gRilAppStatus[SIM_NOT_READY] =
   1924       (RIL_AppStatus){RIL_APPTYPE_SIM,
   1925                       RIL_APPSTATE_DETECTED,
   1926                       RIL_PERSOSUBSTATE_UNKNOWN,
   1927                       NULL,
   1928                       NULL,
   1929                       0,
   1930                       RIL_PINSTATE_ENABLED_NOT_VERIFIED,
   1931                       RIL_PINSTATE_ENABLED_NOT_VERIFIED};
   1932   gRilAppStatus[SIM_READY] = (RIL_AppStatus){
   1933       RIL_APPTYPE_SIM,
   1934       RIL_APPSTATE_READY,
   1935       RIL_PERSOSUBSTATE_READY,
   1936       NULL,
   1937       NULL,
   1938       0,
   1939       RIL_PINSTATE_ENABLED_VERIFIED,
   1940       RIL_PINSTATE_ENABLED_VERIFIED,
   1941   };
   1942   gRilAppStatus[SIM_PIN] = (RIL_AppStatus){RIL_APPTYPE_SIM,
   1943                                            RIL_APPSTATE_PIN,
   1944                                            RIL_PERSOSUBSTATE_UNKNOWN,
   1945                                            NULL,
   1946                                            NULL,
   1947                                            0,
   1948                                            RIL_PINSTATE_ENABLED_NOT_VERIFIED,
   1949                                            RIL_PINSTATE_UNKNOWN};
   1950   gRilAppStatus[SIM_PUK] = (RIL_AppStatus){RIL_APPTYPE_SIM,
   1951                                            RIL_APPSTATE_PUK,
   1952                                            RIL_PERSOSUBSTATE_UNKNOWN,
   1953                                            NULL,
   1954                                            NULL,
   1955                                            0,
   1956                                            RIL_PINSTATE_ENABLED_BLOCKED,
   1957                                            RIL_PINSTATE_UNKNOWN};
   1958   gRilAppStatus[SIM_NETWORK_PERSONALIZATION] =
   1959       (RIL_AppStatus){RIL_APPTYPE_SIM,
   1960                       RIL_APPSTATE_SUBSCRIPTION_PERSO,
   1961                       RIL_PERSOSUBSTATE_SIM_NETWORK,
   1962                       NULL,
   1963                       NULL,
   1964                       0,
   1965                       RIL_PINSTATE_ENABLED_NOT_VERIFIED,
   1966                       RIL_PINSTATE_UNKNOWN};
   1967   gRilAppStatus[RUIM_ABSENT] = (RIL_AppStatus){RIL_APPTYPE_UNKNOWN,
   1968                                                RIL_APPSTATE_UNKNOWN,
   1969                                                RIL_PERSOSUBSTATE_UNKNOWN,
   1970                                                NULL,
   1971                                                NULL,
   1972                                                0,
   1973                                                RIL_PINSTATE_UNKNOWN,
   1974                                                RIL_PINSTATE_UNKNOWN};
   1975   gRilAppStatus[RUIM_NOT_READY] = (RIL_AppStatus){RIL_APPTYPE_RUIM,
   1976                                                   RIL_APPSTATE_DETECTED,
   1977                                                   RIL_PERSOSUBSTATE_UNKNOWN,
   1978                                                   NULL,
   1979                                                   NULL,
   1980                                                   0,
   1981                                                   RIL_PINSTATE_UNKNOWN,
   1982                                                   RIL_PINSTATE_UNKNOWN};
   1983   gRilAppStatus[RUIM_READY] = (RIL_AppStatus){RIL_APPTYPE_RUIM,
   1984                                               RIL_APPSTATE_READY,
   1985                                               RIL_PERSOSUBSTATE_READY,
   1986                                               NULL,
   1987                                               NULL,
   1988                                               0,
   1989                                               RIL_PINSTATE_UNKNOWN,
   1990                                               RIL_PINSTATE_UNKNOWN};
   1991   gRilAppStatus[RUIM_PIN] = (RIL_AppStatus){RIL_APPTYPE_RUIM,
   1992                                             RIL_APPSTATE_PIN,
   1993                                             RIL_PERSOSUBSTATE_UNKNOWN,
   1994                                             NULL,
   1995                                             NULL,
   1996                                             0,
   1997                                             RIL_PINSTATE_ENABLED_NOT_VERIFIED,
   1998                                             RIL_PINSTATE_UNKNOWN};
   1999   gRilAppStatus[RUIM_PUK] = (RIL_AppStatus){RIL_APPTYPE_RUIM,
   2000                                             RIL_APPSTATE_PUK,
   2001                                             RIL_PERSOSUBSTATE_UNKNOWN,
   2002                                             NULL,
   2003                                             NULL,
   2004                                             0,
   2005                                             RIL_PINSTATE_ENABLED_BLOCKED,
   2006                                             RIL_PINSTATE_UNKNOWN};
   2007   gRilAppStatus[RUIM_NETWORK_PERSONALIZATION] =
   2008       (RIL_AppStatus){RIL_APPTYPE_RUIM,
   2009                       RIL_APPSTATE_SUBSCRIPTION_PERSO,
   2010                       RIL_PERSOSUBSTATE_SIM_NETWORK,
   2011                       NULL,
   2012                       NULL,
   2013                       0,
   2014                       RIL_PINSTATE_ENABLED_NOT_VERIFIED,
   2015                       RIL_PINSTATE_UNKNOWN};
   2016 }
   2017 
   2018 /**
   2019  * Get the current card status.
   2020  */
   2021 static void getCardStatus(RIL_Token t) {
   2022   ALOGV("Querying SIM status.");
   2023   RIL_CardStatus_v6 card_status;
   2024 
   2025   if (gSimStatus == SIM_ABSENT) {
   2026     card_status.card_state = RIL_CARDSTATE_ABSENT;
   2027     card_status.num_applications = 0;
   2028   } else {
   2029     card_status.card_state = RIL_CARDSTATE_PRESENT;
   2030     card_status.num_applications = 1;
   2031   }
   2032 
   2033   card_status.universal_pin_state = RIL_PINSTATE_UNKNOWN;
   2034   card_status.gsm_umts_subscription_app_index = -1;
   2035   card_status.cdma_subscription_app_index = -1;
   2036   card_status.ims_subscription_app_index = -1;
   2037 
   2038   // Initialize application status
   2039   for (int i = 0; i < RIL_CARD_MAX_APPS; i++) {
   2040     card_status.applications[i] = gRilAppStatus[SIM_ABSENT];
   2041   }
   2042 
   2043   if (card_status.num_applications > 0) {
   2044     card_status.gsm_umts_subscription_app_index = 0;
   2045 
   2046     card_status.applications[0] = gRilAppStatus[gSimStatus];
   2047     card_status.universal_pin_state = card_status.applications[0].pin1;
   2048     // To enable basic CDMA (currently neither supported nor functional):
   2049     //    card_status.num_applications = 2;
   2050     //    card_status.cdma_subscription_app_index = 1;
   2051     //    card_status.applications[1] =
   2052     //        gRilAppStatus[SIM_Status(gSimStatus + RUIM_ABSENT)];
   2053   }
   2054 
   2055   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &card_status,
   2056                                  sizeof(card_status));
   2057 }
   2058 
   2059 struct SimSession {
   2060   std::string aid;
   2061 };
   2062 
   2063 static int gNextSimSessionId = 1;
   2064 static std::map<int, SimSession> gSimSessions;
   2065 
   2066 static void request_sim_open_channel(void* data, size_t /*datalen*/,
   2067                                      RIL_Token t) {
   2068   char* aid = (char*)data;
   2069   SimSession session;
   2070 
   2071   ALOGV("Requesting new SIM session");
   2072 
   2073   if (aid != NULL) {
   2074     session.aid = aid;
   2075   }
   2076 
   2077   int response = gNextSimSessionId++;
   2078   gSimSessions[response] = session;
   2079 
   2080   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &response, sizeof(response));
   2081 }
   2082 
   2083 static void request_sim_close_channel(void* data, size_t /*datalen*/,
   2084                                       RIL_Token t) {
   2085   int session = *(int*)(data);
   2086 
   2087   ALOGV("Closing SIM session %d", session);
   2088 
   2089   if (gSimSessions.erase(session) == 0) {
   2090     // No such session.
   2091     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   2092   } else {
   2093     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   2094   }
   2095 }
   2096 
   2097 #if VSOC_PLATFORM_SDK_AFTER(K)
   2098 static void request_sim_apdu(void* data, size_t /*datalen*/, RIL_Token t) {
   2099   RIL_SIM_APDU* apdu = (RIL_SIM_APDU*)data;
   2100 
   2101   ALOGV("Requesting APDU: Session %d CLA %d INST %d Params: %d %d %d, data %s",
   2102         apdu->sessionid, apdu->cla, apdu->instruction, apdu->p1, apdu->p2,
   2103         apdu->p3, apdu->data);
   2104 
   2105   if (gSimSessions.find(apdu->sessionid) != gSimSessions.end()) {
   2106     RIL_SIM_IO_Response sr{};
   2107 
   2108     // Fallback / default behavior.
   2109     sr.sw1 = 144;
   2110     sr.sw2 = 0;
   2111     sr.simResponse = NULL;
   2112 
   2113     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
   2114   } else {
   2115     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   2116   }
   2117 }
   2118 #endif
   2119 
   2120 // 0 = Lock is available, but disabled.
   2121 // 1 = Lock is available and enabled,
   2122 // 2 = lock is neither available nor enabled
   2123 static const int kFacilityLockAllDisabled = 0;
   2124 
   2125 static void request_facility_lock(void* data, size_t /*datalen*/, RIL_Token t) {
   2126   char** data_vec = (char**)data;
   2127 
   2128   // TODO(ender): implement this; essentially: AT+CLCK
   2129   // See http://www.activexperts.com/sms-component/at/commands/?at=%2BCLCK
   2130   // and
   2131   // opt/telephony/src/java/com/android/internal/telephony/CommandsInterface.java
   2132   // opt/telephony/src/java/com/android/internal/telephony/uicc/UiccCardApplication.java
   2133 
   2134   ALOGV("Query Facility Lock Code: %s PIN2: %s Service(s): %s AID: %s",
   2135         data_vec[0], data_vec[1], data_vec[2], data_vec[3]);
   2136 
   2137   // TODO(ender): there should be a bit vector of responses for each of the
   2138   // services requested.
   2139   // Depending on lock code, facilities may be unlocked or locked. We report
   2140   // these are all unlocked, regardless of the query.
   2141   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS,
   2142                                  const_cast<int*>(&kFacilityLockAllDisabled),
   2143                                  sizeof(kFacilityLockAllDisabled));
   2144 }
   2145 
   2146 static void request_international_subscriber_id_number(RIL_Token t) {
   2147   // TODO(ender): Reuse MCC and MNC.
   2148   std::string subscriber_id = gCurrentNetworkOperator.c_str();
   2149   subscriber_id += "123456789";
   2150 
   2151   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS,
   2152                                  strdup(subscriber_id.c_str()), sizeof(char*));
   2153 }
   2154 
   2155 static bool gScreenIsOn = true;
   2156 
   2157 static void request_set_screen_state(void* data, size_t /*datalen*/,
   2158                                      RIL_Token t) {
   2159   gScreenIsOn = *(int*)data ? true : false;
   2160   ALOGV("Screen is %s", gScreenIsOn ? "on" : "off");
   2161   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   2162 }
   2163 
   2164 // Unsure which section this belongs in.
   2165 
   2166 static int gModemTtyMode = 1;  // 0 = off, 1 = full, 2 = HCO, 3 = VCO.
   2167 static void request_set_tty_mode(void* data, size_t /*datalen*/, RIL_Token t) {
   2168   int new_tty_mode = *(int*)(data);
   2169   ALOGV("Switching modem TTY mode %d -> %d", gModemTtyMode, new_tty_mode);
   2170 
   2171   if (new_tty_mode >= 0 && new_tty_mode <= 3) {
   2172     gModemTtyMode = new_tty_mode;
   2173     gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   2174   } else {
   2175     gce_ril_env->OnRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
   2176   }
   2177 }
   2178 
   2179 static void request_get_tty_mode(RIL_Token t) {
   2180   ALOGV("Querying TTY mode");
   2181   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &gModemTtyMode,
   2182                                  sizeof(gModemTtyMode));
   2183 }
   2184 
   2185 static bool gImsRegistered = false;
   2186 static int gImsFormat = RADIO_TECH_3GPP;
   2187 
   2188 static void request_ims_registration_state(RIL_Token t) {
   2189   ALOGV("Querying IMS mode");
   2190   int reply[2];
   2191   reply[0] = gImsRegistered;
   2192   reply[1] = gImsFormat;
   2193 
   2194   ALOGV("Requesting IMS Registration state: %d, format=%d ", reply[0],
   2195         reply[1]);
   2196 
   2197   gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, reply, sizeof(reply));
   2198 }
   2199 
   2200 static void gce_ril_on_request(int request, void* data, size_t datalen,
   2201                                RIL_Token t) {
   2202   // Ignore all requests except RIL_REQUEST_GET_SIM_STATUS
   2203   // when RADIO_STATE_UNAVAILABLE.
   2204   if (gRadioPowerState == RADIO_STATE_UNAVAILABLE &&
   2205       request != RIL_REQUEST_GET_SIM_STATUS) {
   2206     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   2207     return;
   2208   }
   2209 
   2210   // Ignore all non-power requests when RADIO_STATE_OFF (except
   2211   // RIL_REQUEST_GET_SIM_STATUS)
   2212   if (gRadioPowerState == RADIO_STATE_OFF &&
   2213       !(request == RIL_REQUEST_RADIO_POWER ||
   2214         request == RIL_REQUEST_GET_SIM_STATUS)) {
   2215     gce_ril_env->OnRequestComplete(t, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
   2216     return;
   2217   }
   2218 
   2219   ALOGV("Received request %d", request);
   2220 
   2221   switch (request) {
   2222     case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS:
   2223       request_query_available_networks(data, datalen, t);
   2224       break;
   2225     case RIL_REQUEST_GET_IMEI:
   2226       request_get_imei(t);
   2227       break;
   2228     case RIL_REQUEST_GET_IMEISV:
   2229       request_get_imei_sv(t);
   2230       break;
   2231     case RIL_REQUEST_DEACTIVATE_DATA_CALL:
   2232       request_teardown_data_call(data, datalen, t);
   2233       break;
   2234     case RIL_REQUEST_SCREEN_STATE:
   2235       request_set_screen_state(data, datalen, t);
   2236       break;
   2237     case RIL_REQUEST_GET_SIM_STATUS:
   2238       getCardStatus(t);
   2239       break;
   2240     case RIL_REQUEST_GET_CURRENT_CALLS:
   2241       request_get_current_calls(data, datalen, t);
   2242       break;
   2243     case RIL_REQUEST_DIAL:
   2244       request_dial(data, datalen, t);
   2245       break;
   2246     case RIL_REQUEST_HANGUP:
   2247       request_hangup(data, datalen, t);
   2248       break;
   2249     case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
   2250       request_hangup_waiting(data, datalen, t);
   2251       break;
   2252     case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
   2253       request_hangup_current(t);
   2254       break;
   2255     case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
   2256       request_switch_current_and_waiting(t);
   2257       break;
   2258     case RIL_REQUEST_ANSWER:
   2259       request_answer_incoming(t);
   2260       break;
   2261     case RIL_REQUEST_SET_MUTE:
   2262       request_set_mute(data, datalen, t);
   2263       break;
   2264     case RIL_REQUEST_GET_MUTE:
   2265       request_get_mute(t);
   2266       break;
   2267     case RIL_REQUEST_CONFERENCE:
   2268       request_combine_multiparty_call(data, datalen, t);
   2269       break;
   2270     case RIL_REQUEST_SEPARATE_CONNECTION:
   2271       request_split_multiparty_call(data, datalen, t);
   2272       break;
   2273     case RIL_REQUEST_UDUB:
   2274       request_udub_on_incoming_calls(t);
   2275       break;
   2276     case RIL_REQUEST_SIGNAL_STRENGTH:
   2277       request_signal_strength(data, datalen, t);
   2278       break;
   2279     case RIL_REQUEST_VOICE_REGISTRATION_STATE:
   2280     case RIL_REQUEST_DATA_REGISTRATION_STATE:
   2281       request_registration_state(request, data, datalen, t);
   2282       break;
   2283     case RIL_REQUEST_OPERATOR:
   2284       request_operator(data, datalen, t);
   2285       break;
   2286     case RIL_REQUEST_RADIO_POWER:
   2287       request_radio_power(data, datalen, t);
   2288       break;
   2289     case RIL_REQUEST_DTMF:
   2290     case RIL_REQUEST_DTMF_START:
   2291       request_send_dtmf(data, datalen, t);
   2292       break;
   2293     case RIL_REQUEST_DTMF_STOP:
   2294       request_send_dtmf_stop(t);
   2295       break;
   2296     case RIL_REQUEST_SEND_SMS:
   2297       request_send_SMS(data, t);
   2298       break;
   2299     case RIL_REQUEST_CDMA_SEND_SMS:
   2300       request_cdma_send_SMS(data, t);
   2301       break;
   2302     case RIL_REQUEST_SETUP_DATA_CALL:
   2303       request_setup_data_call(data, datalen, t);
   2304       break;
   2305     case RIL_REQUEST_SMS_ACKNOWLEDGE:
   2306       request_SMS_acknowledge(data, datalen, t);
   2307       break;
   2308     case RIL_REQUEST_GET_IMSI:
   2309       request_international_subscriber_id_number(t);
   2310       break;
   2311     case RIL_REQUEST_QUERY_FACILITY_LOCK:
   2312       request_facility_lock(data, datalen, t);
   2313       break;
   2314     case RIL_REQUEST_SIM_IO:
   2315       request_SIM_IO(data, datalen, t);
   2316       break;
   2317     case RIL_REQUEST_SEND_USSD:
   2318       request_send_ussd(data, datalen, t);
   2319       break;
   2320     case RIL_REQUEST_CANCEL_USSD:
   2321       request_cancel_ussd(t);
   2322       break;
   2323     case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
   2324       request_set_automatic_network_selection(t);
   2325       break;
   2326     case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL:
   2327       request_set_manual_network_selection(data, datalen, t);
   2328       break;
   2329     case RIL_REQUEST_DATA_CALL_LIST:
   2330       request_data_calllist(data, datalen, t);
   2331       break;
   2332     case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE:
   2333       request_datacall_fail_cause(t);
   2334       break;
   2335     case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
   2336       request_query_network_selection_mode(data, datalen, t);
   2337       break;
   2338     case RIL_REQUEST_OEM_HOOK_RAW:
   2339     case RIL_REQUEST_OEM_HOOK_STRINGS:
   2340       ALOGV("OEM Hooks not supported!");
   2341       gce_ril_env->OnRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
   2342       break;
   2343     case RIL_REQUEST_WRITE_SMS_TO_SIM:
   2344       request_write_sms_to_sim(data, datalen, t);
   2345       break;
   2346     case RIL_REQUEST_DELETE_SMS_ON_SIM:
   2347       request_delete_sms_on_sim(data, datalen, t);
   2348       break;
   2349     case RIL_REQUEST_ENTER_SIM_PIN:
   2350     case RIL_REQUEST_ENTER_SIM_PUK:
   2351     case RIL_REQUEST_ENTER_SIM_PIN2:
   2352     case RIL_REQUEST_ENTER_SIM_PUK2:
   2353     case RIL_REQUEST_CHANGE_SIM_PIN:
   2354     case RIL_REQUEST_CHANGE_SIM_PIN2:
   2355       request_enter_sim_pin(data, datalen, t);
   2356       break;
   2357     case RIL_REQUEST_VOICE_RADIO_TECH: {
   2358       RIL_RadioTechnology tech = getBestVoiceTechnology(gModemCurrentType);
   2359       gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, &tech, sizeof(tech));
   2360       break;
   2361     }
   2362     case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
   2363       request_set_preferred_network_type(request, data, datalen, t);
   2364       break;
   2365     case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
   2366       request_get_preferred_network_type(request, data, datalen, t);
   2367       break;
   2368     case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
   2369       request_get_neighboring_cell_ids(data, datalen, t);
   2370       break;
   2371 #if VSOC_PLATFORM_SDK_AFTER(J_MR1)
   2372     case RIL_REQUEST_GET_CELL_INFO_LIST:
   2373       request_get_cell_info_list(data, datalen, t);
   2374       break;
   2375     case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE:
   2376       request_set_cell_info_list_rate(data, datalen, t);
   2377       break;
   2378 #endif
   2379     case RIL_REQUEST_BASEBAND_VERSION:
   2380       request_baseband_version(t);
   2381       break;
   2382     case RIL_REQUEST_SET_TTY_MODE:
   2383       request_set_tty_mode(data, datalen, t);
   2384       break;
   2385     case RIL_REQUEST_QUERY_TTY_MODE:
   2386       request_get_tty_mode(t);
   2387       break;
   2388 
   2389 #if VSOC_PLATFORM_SDK_AFTER(L)
   2390     case RIL_REQUEST_GET_RADIO_CAPABILITY:
   2391       request_get_radio_capability(t);
   2392       break;
   2393     case RIL_REQUEST_SET_RADIO_CAPABILITY:
   2394       request_set_radio_capability(data, datalen, t);
   2395       break;
   2396 #endif
   2397 #if VSOC_PLATFORM_SDK_AFTER(K)
   2398     case RIL_REQUEST_GET_HARDWARE_CONFIG:
   2399       request_hardware_config(t);
   2400       break;
   2401     case RIL_REQUEST_IMS_REGISTRATION_STATE:
   2402       request_ims_registration_state(t);
   2403       break;
   2404     case RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL:
   2405       request_sim_apdu(data, datalen, t);
   2406       break;
   2407     case RIL_REQUEST_SIM_OPEN_CHANNEL:
   2408       request_sim_open_channel(data, datalen, t);
   2409       break;
   2410     case RIL_REQUEST_SIM_CLOSE_CHANNEL:
   2411       request_sim_close_channel(data, datalen, t);
   2412       break;
   2413 #endif
   2414 #if VSOC_PLATFORM_SDK_AFTER(J_MR2)
   2415     case RIL_REQUEST_IMS_SEND_SMS:
   2416       request_ims_send_SMS(data, datalen, t);
   2417       break;
   2418 
   2419     case RIL_REQUEST_SET_INITIAL_ATTACH_APN:
   2420       ALOGW("INITIAL ATTACH APN");
   2421       gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   2422       break;
   2423 
   2424 #endif
   2425     case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING:
   2426       gce_ril_env->OnRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
   2427       break;
   2428     case RIL_REQUEST_DEVICE_IDENTITY:
   2429       request_device_identity(request, data, datalen, t);
   2430       break;
   2431     case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
   2432       request_cdma_get_subscription_source(request, data, datalen, t);
   2433       break;
   2434     case RIL_REQUEST_CDMA_SUBSCRIPTION:
   2435       request_cdma_subscription(request, data, datalen, t);
   2436       break;
   2437     case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
   2438       request_cdma_set_subscription_source(request, data, datalen, t);
   2439       break;
   2440     case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:
   2441       request_cdma_get_roaming_preference(request, data, datalen, t);
   2442       break;
   2443     case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
   2444       request_cdma_set_roaming_preference(request, data, datalen, t);
   2445       break;
   2446     case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
   2447       request_exit_emergency_mode(data, datalen, t);
   2448       break;
   2449     default:
   2450       ALOGE("Request %d not supported.", request);
   2451       gce_ril_env->OnRequestComplete(t, RIL_E_REQUEST_NOT_SUPPORTED, NULL, 0);
   2452       break;
   2453   }
   2454 }
   2455 
   2456 #define VSOC_RIL_VERSION 6
   2457 
   2458 static const RIL_RadioFunctions ril_callbacks = {
   2459     VSOC_RIL_VERSION,     gce_ril_on_request, gce_ril_current_state,
   2460     gce_ril_on_supports, gce_ril_on_cancel,  gce_ril_get_version};
   2461 
   2462 extern "C" {
   2463 
   2464 const RIL_RadioFunctions* RIL_Init(const struct RIL_Env* env, int /*argc*/,
   2465                                    char** /*argv*/) {
   2466   time(&gce_ril_start_time);
   2467   gce_ril_env = env;
   2468 
   2469   TearDownNetworkInterface();
   2470 
   2471   init_modem_supported_network_types();
   2472   init_modem_technologies();
   2473   init_virtual_network();
   2474   init_sim_file_system();
   2475   init_sim_status();
   2476 
   2477   return &ril_callbacks;
   2478 }
   2479 
   2480 }  // extern "C"
   2481