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