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