1 //
2 // Copyright (C) 2020 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 is 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 #include "host/commands/modem_simulator/sim_service.h"
17
18 #include <android-base/logging.h>
19 #include <tinyxml2.h>
20
21 #include "common/libs/utils/files.h"
22 #include "host/commands/modem_simulator/device_config.h"
23 #include "host/commands/modem_simulator/network_service.h"
24 #include "host/commands/modem_simulator/pdu_parser.h"
25 #include "host/commands/modem_simulator/nvram_config.h"
26
27 namespace cuttlefish {
28
29 const std::pair<int, int> kSimPinSizeRange(4, 8);
30 constexpr int kSimPukSize = 8;
31 constexpr int kSimPinMaxRetryTimes = 3;
32 constexpr int kSimPukMaxRetryTimes = 10;
33 static const std::string kDefaultPinCode = "1234";
34 static const std::string kDefaultPukCode = "12345678";
35
36 static const std::string MF_SIM = "3F00";
37 static const std::string DF_TELECOM = "7F10";
38 static const std::string DF_PHONEBOOK = "5F3A";
39 static const std::string DF_GRAPHICS = "5F50";
40 static const std::string DF_GSM = "7F20";
41 static const std::string DF_CDMA = "7F25";
42 static const std::string DF_ADF = "7FFF"; // UICC access
43
44 // In an ADN record, everything but the alpha identifier
45 // is in a footer that's 14 bytes
46 constexpr int kFooterSizeBytes = 14;
47 // Maximum size of the un-extended number field
48 constexpr int kMaxNumberSizeBytes = 11;
49
50 constexpr int kMaxLogicalChannels = 3;
51
52 const std::map<SimService::SimStatus, std::string> gSimStatusResponse = {
53 {SimService::SIM_STATUS_ABSENT, ModemService::kCmeErrorSimNotInserted},
54 {SimService::SIM_STATUS_NOT_READY, ModemService::kCmeErrorSimBusy},
55 {SimService::SIM_STATUS_READY, "+CPIN: READY"},
56 {SimService::SIM_STATUS_PIN, "+CPIN: SIM PIN"},
57 {SimService::SIM_STATUS_PUK, "+CPIN: SIM PUK"},
58 };
59
60 /* SimFileSystem */
GetRootElement()61 XMLElement* SimService::SimFileSystem::GetRootElement() {
62 return doc.RootElement();
63 }
64
GetCommonIccEFPath(EFId efid)65 std::string SimService::SimFileSystem::GetCommonIccEFPath(EFId efid) {
66 switch (efid) {
67 case EF_ADN:
68 case EF_FDN:
69 case EF_MSISDN:
70 case EF_SDN:
71 case EF_EXT1:
72 case EF_EXT2:
73 case EF_EXT3:
74 case EF_PSI:
75 return MF_SIM + DF_TELECOM;
76
77 case EF_ICCID:
78 case EF_PL:
79 return MF_SIM;
80 case EF_PBR:
81 // we only support global phonebook.
82 return MF_SIM + DF_TELECOM + DF_PHONEBOOK;
83 case EF_IMG:
84 return MF_SIM + DF_TELECOM + DF_GRAPHICS;
85 default:
86 return {};
87 }
88 }
89
GetUsimEFPath(EFId efid)90 std::string SimService::SimFileSystem::GetUsimEFPath(EFId efid) {
91 switch(efid) {
92 case EF_SMS:
93 case EF_EXT5:
94 case EF_EXT6:
95 case EF_MWIS:
96 case EF_MBI:
97 case EF_SPN:
98 case EF_AD:
99 case EF_MBDN:
100 case EF_PNN:
101 case EF_OPL:
102 case EF_SPDI:
103 case EF_SST:
104 case EF_CFIS:
105 case EF_MAILBOX_CPHS:
106 case EF_VOICE_MAIL_INDICATOR_CPHS:
107 case EF_CFF_CPHS:
108 case EF_SPN_CPHS:
109 case EF_SPN_SHORT_CPHS:
110 case EF_FDN:
111 case EF_SDN:
112 case EF_EXT3:
113 case EF_MSISDN:
114 case EF_EXT2:
115 case EF_INFO_CPHS:
116 case EF_CSP_CPHS:
117 case EF_GID1:
118 case EF_GID2:
119 case EF_LI:
120 case EF_PLMN_W_ACT:
121 case EF_OPLMN_W_ACT:
122 case EF_HPLMN_W_ACT:
123 case EF_EHPLMN:
124 case EF_FPLMN:
125 case EF_LRPLMNSI:
126 case EF_HPPLMN:
127 return MF_SIM + DF_ADF;
128
129 case EF_PBR:
130 // we only support global phonebook.
131 return MF_SIM + DF_TELECOM + DF_PHONEBOOK;
132 default:
133 std::string path = GetCommonIccEFPath(efid);
134 if (path.empty()) {
135 // The EFids in USIM phone book entries are decided by the card manufacturer.
136 // So if we don't match any of the cases above and if it's a USIM return
137 // the phone book path.
138 return MF_SIM + DF_TELECOM + DF_PHONEBOOK;
139 }
140 return path;
141 }
142 }
143
FindAttribute(XMLElement * parent,const std::string & attr_name,const std::string & attr_value)144 XMLElement* SimService::SimFileSystem::FindAttribute(XMLElement *parent,
145 const std::string& attr_name,
146 const std::string& attr_value) {
147 if (parent == nullptr) {
148 return nullptr;
149 }
150
151 XMLElement* child = parent->FirstChildElement();
152 while (child) {
153 const XMLAttribute *attr = child->FindAttribute(attr_name.c_str());
154 if (attr && attr->Value() == attr_value) {
155 break;
156 }
157 child = child->NextSiblingElement();
158 }
159 return child;
160 };
161
AppendNewElement(XMLElement * parent,const char * name)162 XMLElement* SimService::SimFileSystem::AppendNewElement(XMLElement* parent,
163 const char* name) {
164 auto element = doc.NewElement(name);
165 parent->InsertEndChild(element);
166 return element;
167 }
168
AppendNewElementWithText(XMLElement * parent,const char * name,const char * text)169 XMLElement* SimService::SimFileSystem::AppendNewElementWithText(
170 XMLElement* parent, const char* name, const char* text) {
171 auto element = doc.NewElement(name);
172 auto xml_text = doc.NewText(text);
173 element->InsertEndChild(xml_text);
174 parent->InsertEndChild(element);
175 return element;
176 }
177
178 /* PinStatus */
CheckPasswordValid(std::string_view password)179 bool SimService::PinStatus::CheckPasswordValid(std::string_view password) {
180 for (int i = 0; i < password.size(); i++) {
181 int c = (int)password[i];
182 if (c >= 48 && c <= 57) {
183 continue;
184 } else {
185 return false;
186 }
187 }
188 return true;
189 }
190
VerifyPIN(const std::string_view pin)191 bool SimService::PinStatus::VerifyPIN(const std::string_view pin) {
192 if (pin.size() < kSimPinSizeRange.first || pin.size() > kSimPinSizeRange.second) {
193 return false;
194 }
195
196 if (!CheckPasswordValid(pin)) {
197 return false;
198 }
199
200 if (pin_remaining_times_ <= 0) {
201 return false;
202 }
203
204 std::string_view temp(pin_);
205 if (pin == temp) { // C++20 remove Operator!=
206 pin_remaining_times_ = kSimPinMaxRetryTimes;
207 return true;
208 }
209
210 pin_remaining_times_ -= 1;
211 return false;
212 }
213
VerifyPUK(const std::string_view puk)214 bool SimService::PinStatus::VerifyPUK(const std::string_view puk) {
215 if (puk.size() != kSimPukSize) {
216 return false;
217 }
218
219 if (!CheckPasswordValid(puk)) {
220 return false;
221 }
222
223 if (puk_remaining_times_ <= 0) {
224 return false;
225 }
226
227 std::string_view temp(puk_);
228 if (puk == temp) { // C++20 remove Operator!=
229 pin_remaining_times_ = kSimPinMaxRetryTimes;
230 puk_remaining_times_ = kSimPukMaxRetryTimes;
231 return true;
232 }
233
234 puk_remaining_times_ -= 1;
235 return false;
236 }
237
ChangePIN(ChangeMode mode,const std::string_view pin_or_puk,const std::string_view new_pin)238 bool SimService::PinStatus::ChangePIN(ChangeMode mode,
239 const std::string_view pin_or_puk,
240 const std::string_view new_pin) {
241 auto length = new_pin.length();
242 if (length < kSimPinSizeRange.first || length > kSimPinSizeRange.second) {
243 LOG(ERROR) << "Invalid digit number for PIN";
244 return false;
245 }
246
247 bool result = false;
248 if (mode == WITH_PIN) { // using old pin to change pin
249 result = VerifyPIN(pin_or_puk);
250 } else if (mode == WITH_PUK) { // using puk to change pin
251 result = VerifyPUK(pin_or_puk);
252 }
253
254 if (!result) {
255 LOG(ERROR) << "Incorrect PIN or PUK";
256 return false;
257 }
258
259 if (!CheckPasswordValid(new_pin)) {
260 return false;
261 }
262
263 std::string temp(new_pin);
264 pin_ = temp;
265 return true;
266 }
267
ChangePUK(const std::string_view puk,const std::string_view new_puk)268 bool SimService::PinStatus::ChangePUK(const std::string_view puk,
269 const std::string_view new_puk) {
270 bool result = VerifyPUK(puk);
271 if (!result) {
272 LOG(ERROR) << "Incorrect PUK or no retry times";
273 return false;
274 }
275
276 if (new_puk.length() != kSimPukSize) {
277 LOG(ERROR) << "Invalid digit number for PUK";
278 return false;
279 }
280
281 std::string temp(new_puk);
282 puk_ = temp;
283 return true;
284 };
285
SimService(int32_t service_id,ChannelMonitor * channel_monitor,ThreadLooper * thread_looper)286 SimService::SimService(int32_t service_id, ChannelMonitor* channel_monitor,
287 ThreadLooper* thread_looper)
288 : ModemService(service_id, this->InitializeCommandHandlers(),
289 channel_monitor, thread_looper) {
290 InitializeServiceState();
291 }
292
InitializeCommandHandlers()293 std::vector<CommandHandler> SimService::InitializeCommandHandlers() {
294 std::vector<CommandHandler> command_handlers = {
295 CommandHandler(
296 "+CPIN?",
297 [this](const Client& client) { this->HandleSIMStatusReq(client); }),
298 CommandHandler("+CPIN=",
299 [this](const Client& client, std::string& cmd) {
300 this->HandleChangeOrEnterPIN(client, cmd);
301 }),
302 CommandHandler("+CRSM=",
303 [this](const Client& client, std::string& cmd) {
304 this->HandleSIM_IO(client, cmd);
305 }),
306 CommandHandler("+CSIM=",
307 [this](const Client& client, std::string& cmd) {
308 this->HandleCSIM_IO(client, cmd);
309 }),
310 CommandHandler(
311 "+CIMI",
312 [this](const Client& client) { this->HandleGetIMSI(client); }),
313 CommandHandler(
314 "+CICCID",
315 [this](const Client& client) { this->HandleGetIccId(client); }),
316 CommandHandler("+CLCK=",
317 [this](const Client& client, std::string& cmd) {
318 this->HandleFacilityLock(client, cmd);
319 }),
320 CommandHandler("+CCHO=",
321 [this](const Client& client, std::string& cmd) {
322 this->HandleOpenLogicalChannel(client, cmd);
323 }),
324 CommandHandler("+CCHC=",
325 [this](const Client& client, std::string& cmd) {
326 this->HandleCloseLogicalChannel(client, cmd);
327 }),
328 CommandHandler("+CGLA=",
329 [this](const Client& client, std::string& cmd) {
330 this->HandleTransmitLogicalChannel(client, cmd);
331 }),
332 CommandHandler("+CPWD=",
333 [this](const Client& client, std::string& cmd) {
334 this->HandleChangePassword(client, cmd);
335 }),
336 CommandHandler("+CPINR=",
337 [this](const Client& client, std::string& cmd) {
338 this->HandleQueryRemainTimes(client, cmd);
339 }),
340 CommandHandler("+CCSS",
341 [this](const Client& client, std::string& cmd) {
342 this->HandleCdmaSubscriptionSource(client, cmd);
343 }),
344 CommandHandler("+WRMP",
345 [this](const Client& client, std::string& cmd) {
346 this->HandleCdmaRoamingPreference(client, cmd);
347 }),
348 CommandHandler("^MBAU=",
349 [this](const Client& client, std::string& cmd) {
350 this->HandleSimAuthentication(client, cmd);
351 }),
352 CommandHandler("+REMOTEUPADATEPHONENUMBER",
353 [this](const Client& client, std::string& cmd) {
354 this->HandlePhoneNumberUpdate(client,cmd);
355 }),
356 };
357 return (command_handlers);
358 }
359
InitializeServiceState()360 void SimService::InitializeServiceState() {
361 InitializeSimFileSystemAndSimState();
362
363 InitializeFacilityLock();
364
365 // Max logical channels: 3
366 logical_channels_ = {
367 LogicalChannel(1), LogicalChannel(2), LogicalChannel(kMaxLogicalChannels),
368 };
369 }
370
InitializeSimFileSystemAndSimState()371 void SimService::InitializeSimFileSystemAndSimState() {
372 auto nvram_config = NvramConfig::Get();
373 auto sim_type = nvram_config->sim_type();
374 std::stringstream ss;
375 if (sim_type == 2) { // Special sim card for CtsCarrierApiTestCases
376 ss << "iccprofile_for_sim" << service_id_ << "_for_CtsCarrierApiTestCases.xml";
377 } else {
378 ss << "iccprofile_for_sim" << service_id_ << ".xml";
379 }
380 auto icc_profile_name = ss.str();
381
382 auto icc_profile_path = cuttlefish::modem::DeviceConfig::PerInstancePath(
383 icc_profile_name.c_str());
384 std::string file = icc_profile_path;
385
386 if (!cuttlefish::FileExists(icc_profile_path) ||
387 !cuttlefish::FileHasContent(icc_profile_path.c_str())) {
388 ss.clear();
389 ss.str("");
390
391 if (sim_type == 2) { // Special sim card for CtsCarrierApiTestCases
392 ss << "etc/modem_simulator/files/iccprofile_for_sim" << service_id_
393 << "_for_CtsCarrierApiTestCases.xml";
394 } else {
395 ss << "etc/modem_simulator/files/iccprofile_for_sim" << service_id_ << ".xml";
396 }
397
398 auto etc_file_path =
399 cuttlefish::modem::DeviceConfig::DefaultHostArtifactsPath(ss.str());
400 if (!cuttlefish::FileExists(etc_file_path) || !cuttlefish::FileHasContent(etc_file_path)) {
401 sim_status_ = SIM_STATUS_ABSENT;
402 return;
403 }
404 file = etc_file_path;
405 }
406
407 sim_file_system_.file_path = icc_profile_path;
408 auto err = sim_file_system_.doc.LoadFile(file.c_str());
409 if (err != tinyxml2::XML_SUCCESS) {
410 LOG(ERROR) << "Unable to load XML file '" << file << " ', error " << err;
411 sim_status_ = SIM_STATUS_ABSENT;
412 return;
413 }
414
415 XMLElement *root = sim_file_system_.GetRootElement();
416 if (!root) {
417 LOG(ERROR) << "Unable to find root element: IccProfile";
418 sim_status_ = SIM_STATUS_ABSENT;
419 return;
420 }
421
422 // Default value if iccprofile not configure pin state
423 sim_status_ = SIM_STATUS_READY;
424 pin1_status_.pin_ = kDefaultPinCode;
425 pin1_status_.puk_ = kDefaultPukCode;
426 pin1_status_.pin_remaining_times_ = kSimPinMaxRetryTimes;
427 pin1_status_.puk_remaining_times_ = kSimPukMaxRetryTimes;
428 pin2_status_.pin_ = kDefaultPinCode;
429 pin2_status_.puk_ = kDefaultPukCode;
430 pin2_status_.pin_remaining_times_ = kSimPinMaxRetryTimes;
431 pin2_status_.puk_remaining_times_ = kSimPukMaxRetryTimes;
432
433 XMLElement *pin_profile = root->FirstChildElement("PinProfile");
434 if (pin_profile) {
435 // Pin1 status
436 auto pin_state = pin_profile->FirstChildElement("PINSTATE");
437 if (pin_state) {
438 std::string state = pin_state->GetText();
439 if (state == "PINSTATE_ENABLED_NOT_VERIFIED") {
440 sim_status_ = SIM_STATUS_PIN;
441 } else if (state == "PINSTATE_ENABLED_BLOCKED") {
442 sim_status_ = SIM_STATUS_PUK;
443 }
444 }
445 auto pin_code = pin_profile->FirstChildElement("PINCODE");
446 if (pin_code) pin1_status_.pin_ = pin_code->GetText();
447
448 auto puk_code = pin_profile->FirstChildElement("PUKCODE");
449 if (puk_code) pin1_status_.puk_ = puk_code->GetText();
450
451 auto pin_remaining_times = pin_profile->FirstChildElement("PINREMAINTIMES");
452 if (pin_remaining_times) {
453 pin1_status_.pin_remaining_times_ = std::stoi(pin_remaining_times->GetText());
454 }
455
456 auto puk_remaining_times = pin_profile->FirstChildElement("PUKREMAINTIMES");
457 if (puk_remaining_times) {
458 pin1_status_.puk_remaining_times_ = std::stoi(puk_remaining_times->GetText());
459 }
460
461 // Pin2 status
462 auto pin2_code = pin_profile->FirstChildElement("PIN2CODE");
463 if (pin2_code) pin2_status_.pin_ = pin2_code->GetText();
464
465 auto puk2_code = pin_profile->FirstChildElement("PUK2CODE");
466 if (puk2_code) pin2_status_.puk_ = puk2_code->GetText();
467
468 auto pin2_remaining_times = pin_profile->FirstChildElement("PIN2REMAINTIMES");
469 if (pin2_remaining_times) {
470 pin2_status_.pin_remaining_times_ = std::stoi(pin2_remaining_times->GetText());
471 }
472
473 auto puk2_remaining_times = pin_profile->FirstChildElement("PUK2REMAINTIMES");
474 if (puk2_remaining_times) {
475 pin2_status_.puk_remaining_times_ = std::stoi(puk2_remaining_times->GetText());
476 }
477 }
478 }
479
InitializeFacilityLock()480 void SimService::InitializeFacilityLock() {
481 /* Default disable */
482 facility_lock_ = {
483 {"SC", FacilityLock(FacilityLock::LockStatus::DISABLE)},
484 {"FD", FacilityLock(FacilityLock::LockStatus::DISABLE)},
485 {"AO", FacilityLock(FacilityLock::LockStatus::DISABLE)},
486 {"OI", FacilityLock(FacilityLock::LockStatus::DISABLE)},
487 {"OX", FacilityLock(FacilityLock::LockStatus::DISABLE)},
488 {"AI", FacilityLock(FacilityLock::LockStatus::DISABLE)},
489 {"IR", FacilityLock(FacilityLock::LockStatus::DISABLE)},
490 {"AB", FacilityLock(FacilityLock::LockStatus::DISABLE)},
491 {"AG", FacilityLock(FacilityLock::LockStatus::DISABLE)},
492 {"AC", FacilityLock(FacilityLock::LockStatus::DISABLE)},
493 };
494
495 XMLElement *root = sim_file_system_.GetRootElement();
496 if (!root) {
497 LOG(ERROR) << "Unable to find root element: IccProfile";
498 sim_status_ = SIM_STATUS_ABSENT;
499 return;
500 }
501
502 XMLElement *facility_lock = root->FirstChildElement("FacilityLock");
503 if (!facility_lock) {
504 LOG(ERROR) << "Unable to find element: FacilityLock";
505 return;
506 }
507
508 for (auto iter = facility_lock_.begin(); iter != facility_lock_.end(); ++iter) {
509 auto lock_status = facility_lock->FirstChildElement(iter->first.c_str());
510 if (lock_status) {
511 std::string state = lock_status->GetText();
512 if (state == "ENABLE") {
513 iter->second.lock_status = FacilityLock::LockStatus::ENABLE;
514 }
515 }
516 }
517 }
518
SavePinStateToIccProfile()519 void SimService::SavePinStateToIccProfile() {
520 XMLElement *root = sim_file_system_.GetRootElement();
521 if (!root) {
522 LOG(ERROR) << "Unable to find root element: IccProfile";
523 sim_status_ = SIM_STATUS_ABSENT;
524 return;
525 }
526
527 XMLElement *pin_profile = root->FirstChildElement("PinProfile");
528 if (!pin_profile) {
529 pin_profile = sim_file_system_.AppendNewElement(root, "PinProfile");
530 }
531
532 const char* text = "PINSTATE_UNKNOWN";
533
534 if (sim_status_ == SIM_STATUS_PUK) {
535 text = "PINSTATE_ENABLED_BLOCKED";
536 } else {
537 auto iter = facility_lock_.find("SC");
538 if (iter != facility_lock_.end()) {
539 if (iter->second.lock_status == FacilityLock::ENABLE) {
540 text = "PINSTATE_ENABLED_NOT_VERIFIED";
541 }
542 }
543 }
544
545 // Pin1 status
546 auto pin_state = pin_profile->FirstChildElement("PINSTATE");
547 if (!pin_state) {
548 pin_state = sim_file_system_.AppendNewElementWithText(pin_profile, "PINSTATE", text);
549 } else {
550 pin_state->SetText(text);
551 }
552
553 auto pin_code = pin_profile->FirstChildElement("PINCODE");
554 if (!pin_code) {
555 pin_code = sim_file_system_.AppendNewElementWithText(pin_profile, "PINCODE",
556 pin1_status_.pin_.c_str());
557 } else {
558 pin_code->SetText(pin1_status_.pin_.c_str());
559 }
560
561 auto puk_code = pin_profile->FirstChildElement("PUKCODE");
562 if (!puk_code) {
563 puk_code = sim_file_system_.AppendNewElementWithText(pin_profile, "PUKCODE",
564 pin1_status_.puk_.c_str());
565 } else {
566 puk_code->SetText(pin1_status_.puk_.c_str());
567 }
568
569 std::stringstream ss;
570 ss << pin1_status_.pin_remaining_times_;
571
572 auto pin_remaining_times = pin_profile->FirstChildElement("PINREMAINTIMES");
573 if (!pin_remaining_times) {
574 pin_remaining_times = sim_file_system_.AppendNewElementWithText(pin_profile,
575 "PINREMAINTIMES", ss.str().c_str());
576 } else {
577 pin_remaining_times->SetText(ss.str().c_str());
578 }
579 ss.clear();
580 ss.str("");
581 ss << pin1_status_.puk_remaining_times_;
582
583 auto puk_remaining_times = pin_profile->FirstChildElement("PUKREMAINTIMES");
584 if (!puk_remaining_times) {
585 puk_remaining_times = sim_file_system_.AppendNewElementWithText(pin_profile,
586 "PUKREMAINTIMES", ss.str().c_str());
587 } else {
588 puk_remaining_times->SetText(ss.str().c_str());
589 }
590
591 // Pin2 status
592 auto pin2_code = pin_profile->FirstChildElement("PIN2CODE");
593 if (!pin2_code) {
594 pin2_code = sim_file_system_.AppendNewElementWithText(pin_profile, "PIN2CODE",
595 pin2_status_.pin_.c_str());
596 } else {
597 pin2_code->SetText(pin2_status_.pin_.c_str());
598 }
599
600 auto puk2_code = pin_profile->FirstChildElement("PUK2CODE");
601 if (!puk2_code) {
602 puk2_code = sim_file_system_.AppendNewElementWithText(pin_profile, "PUK2CODE",
603 pin2_status_.puk_.c_str());
604 } else {
605 puk2_code->SetText(pin2_status_.puk_.c_str());
606 }
607
608 ss.clear();
609 ss.str("");
610 ss << pin2_status_.pin_remaining_times_;
611
612 auto pin2_remaining_times = pin_profile->FirstChildElement("PIN2REMAINTIMES");
613 if (!pin2_remaining_times) {
614 pin2_remaining_times = sim_file_system_.AppendNewElementWithText(pin_profile,
615 "PINREMAINTIMES", ss.str().c_str());
616 } else {
617 pin2_remaining_times->SetText(ss.str().c_str());
618 }
619 ss.clear();
620 ss.str("");
621 ss << pin2_status_.puk_remaining_times_;
622
623 auto puk2_remaining_times = pin_profile->FirstChildElement("PUK2REMAINTIMES");
624 if (!puk2_remaining_times) {
625 puk2_remaining_times = sim_file_system_.AppendNewElementWithText(pin_profile,
626 "PUK2REMAINTIMES", ss.str().c_str());
627 } else {
628 puk2_remaining_times->SetText(ss.str().c_str());
629 }
630
631 // Save file
632 sim_file_system_.doc.SaveFile(sim_file_system_.file_path.c_str());
633 }
634
SaveFacilityLockToIccProfile()635 void SimService::SaveFacilityLockToIccProfile() {
636 XMLElement *root = sim_file_system_.GetRootElement();
637 if (!root) {
638 LOG(ERROR) << "Unable to find root element: IccProfile";
639 sim_status_ = SIM_STATUS_ABSENT;
640 return;
641 }
642
643 XMLElement *facility_lock = root->FirstChildElement("FacilityLock");
644 if (!facility_lock) {
645 facility_lock = sim_file_system_.AppendNewElement(root, "FacilityLock");
646 }
647
648 const char* text = "DISABLE";
649
650 for (auto iter = facility_lock_.begin(); iter != facility_lock_.end(); ++iter) {
651 if (iter->second.lock_status == FacilityLock::LockStatus::ENABLE) {
652 text = "ENABLE";
653 } else {
654 text = "DISABLE";
655 }
656 auto element = facility_lock->FirstChildElement(iter->first.c_str());
657 if (!element) {
658 element = sim_file_system_.AppendNewElementWithText(facility_lock,
659 iter->first.c_str(), text);
660 } else {
661 element->SetText(text);
662 }
663 }
664
665 sim_file_system_.doc.SaveFile(sim_file_system_.file_path.c_str());
666
667 InitializeSimFileSystemAndSimState();
668 InitializeFacilityLock();
669 }
670
IsFDNEnabled()671 bool SimService::IsFDNEnabled() {
672 auto iter = facility_lock_.find("FD");
673 if (iter != facility_lock_.end() &&
674 iter->second.lock_status == FacilityLock::LockStatus::ENABLE) {
675 return true;
676 }
677 return false;
678 }
679
IsFixedDialNumber(std::string_view number)680 bool SimService::IsFixedDialNumber(std::string_view number) {
681 XMLElement *root = sim_file_system_.GetRootElement();
682 if (!root) return false;
683
684 auto path = SimFileSystem::GetUsimEFPath(SimFileSystem::EFId::EF_FDN);
685
686 size_t pos = 0;
687 auto parent = root;
688 while (pos < path.length()) {
689 std::string sub_path(path.substr(pos, 4));
690 auto app = SimFileSystem::FindAttribute(parent, "path", sub_path);
691 if (!app) return false;
692 pos += 4;
693 parent = app;
694 }
695
696 XMLElement* ef = SimFileSystem::FindAttribute(parent, "id", "6F3B");
697 if (!ef) return false;
698
699 XMLElement *final = ef->FirstChildElement("SIMIO");
700 while (final) {
701 std::string record = final->GetText();
702 int footerOffset = record.length() - kFooterSizeBytes * 2;
703 int numberLength = (record[footerOffset] - '0') * 16 +
704 record[footerOffset + 1] - '0';
705 if (numberLength > kMaxNumberSizeBytes) { // Invalid number length
706 final = final->NextSiblingElement("SIMIO");
707 continue;
708 }
709
710 std::string bcd_fdn = "";
711 if (numberLength * 2 == 16) { // Skip Type(91) and Country Code(68)
712 bcd_fdn = record.substr(footerOffset + 6, numberLength * 2 - 4);
713 } else { // Skip Type(81)
714 bcd_fdn = record.substr(footerOffset + 4, numberLength * 2 - 2);
715 }
716
717 std::string fdn = PDUParser::BCDToString(bcd_fdn);
718 if (fdn == number) {
719 return true;
720 }
721 final = final->NextSiblingElement("SIMIO");
722 }
723
724 return false;
725 }
726
GetIccProfile()727 XMLElement* SimService::GetIccProfile() {
728 return sim_file_system_.GetRootElement();
729 }
730
GetPhoneNumber()731 std::string SimService::GetPhoneNumber() {
732 XMLElement* final = GetPhoneNumberElement();
733 if (!final) return "";
734 std::string record = final->GetText();
735 int footerOffset = record.length() - kFooterSizeBytes * 2;
736 int numberLength = (record[footerOffset] - '0') * 16 +
737 record[footerOffset + 1] - '0';
738 if (numberLength > kMaxNumberSizeBytes) { // Invalid number length
739 return "";
740 }
741
742 std::string bcd_number = "";
743 if (numberLength * 2 == 16) { // Skip Type(91) and Country Code(68)
744 bcd_number = record.substr(footerOffset + 6, numberLength * 2 - 4);
745 } else { // Skip Type(81)
746 bcd_number = record.substr(footerOffset + 4, numberLength * 2 - 2);
747 }
748
749 return PDUParser::BCDToString(bcd_number);
750 }
751
SetPhoneNumber(std::string_view number)752 bool SimService::SetPhoneNumber(std::string_view number) {
753 if (number.size() > kMaxNumberSizeBytes) { // Invalid number length
754 return false;
755 }
756 XMLElement* elem = GetPhoneNumberElement();
757 if (!elem) return false;
758 std::string record = elem->GetText();
759 int footerOffset = record.length() - kFooterSizeBytes * 2;
760 std::string bcd_number = PDUParser::StringToBCD(number);
761 int newLength = 0;
762 // Skip Type(91) and Country Code(68)
763 if (number.size() == 12 && number.compare("68") == 0) {
764 record.replace(footerOffset + 6, bcd_number.size(), bcd_number);
765 newLength = 8;
766 } else { // Skip Type(81)
767 record.replace(footerOffset + 4, bcd_number.size(), bcd_number);
768 newLength = (bcd_number.size() + 2) / 2;
769 }
770
771 record[footerOffset] = '0' + newLength / 16;
772 record[footerOffset + 1] = '0' + (newLength % 16);
773
774 elem->SetText(record.c_str());
775 sim_file_system_.doc.SaveFile(sim_file_system_.file_path.c_str());
776 return true;
777 }
778
GetSimStatus() const779 SimService::SimStatus SimService::GetSimStatus() const {
780 return sim_status_;
781 }
782
GetSimOperator()783 std::string SimService::GetSimOperator() {
784 XMLElement *root = sim_file_system_.GetRootElement();
785 if (!root) return "";
786
787 XMLElement* mf = SimFileSystem::FindAttribute(root, "path", MF_SIM);
788 if (!mf) return "";
789
790 XMLElement* df = SimFileSystem::FindAttribute(mf, "path", DF_ADF);
791 if (!df) return "";
792
793 XMLElement* ef = SimFileSystem::FindAttribute(df, "id", "6F07");
794 if (!ef) return "";
795
796 XMLElement *cimi = ef->FirstChildElement("CIMI");
797 if (!cimi) return "";
798 std::string imsi = cimi->GetText();
799
800 ef = SimFileSystem::FindAttribute(df, "id", "6FAD");
801 if (!ef) return "";
802
803 XMLElement *sim_io = ef->FirstChildElement("SIMIO");
804 while (sim_io) {
805 const XMLAttribute *attr_cmd = sim_io->FindAttribute("cmd");
806 std::string attr_value = attr_cmd ? attr_cmd->Value() : "";
807 if (attr_cmd && attr_value == "B0") {
808 break;
809 }
810
811 sim_io = sim_io->NextSiblingElement("SIMIO");
812 }
813
814 if (!sim_io) return "";
815
816 std::string length = sim_io->GetText();
817 int mnc_size = std::stoi(length.substr(length.size() -2));
818
819 return imsi.substr(0, 3 + mnc_size);
820 }
821
SetupDependency(NetworkService * net)822 void SimService::SetupDependency(NetworkService* net) {
823 network_service_ = net;
824 }
825
826 /**
827 * AT+CPIN
828 * Set command sends to the MT a password which is necessary before it can be
829 * operated.
830 * Read command returns an alphanumeric string indicating whether some
831 * password is required or not.
832 *
833 * Command Possible response(s)
834 * +CPIN=<pin>[,<newpin>] +CME ERROR: <err>
835 * +CPIN? +CPIN: <code>
836 * +CME ERROR: <err>
837 * <pin>, <newpin>: string type values.
838 * <code> values reserved by the present document:
839 * READY MT is not pending for any password
840 * SIM PIN MT is waiting SIM PIN to be given
841 * SIM PUK MT is waiting SIM PUK to be given
842 *
843 * see RIL_REQUEST_GET_SIM_STATUS in RIL
844 */
HandleSIMStatusReq(const Client & client)845 void SimService::HandleSIMStatusReq(const Client& client) {
846 std::vector<std::string> responses;
847 auto iter = gSimStatusResponse.find(sim_status_);
848 if (iter != gSimStatusResponse.end()) {
849 responses.push_back(iter->second);
850 responses.push_back("OK");
851 } else {
852 sim_status_ = SIM_STATUS_ABSENT;
853 responses.push_back(kCmeErrorSimNotInserted);
854 }
855 client.SendCommandResponse(responses);
856 }
857
858 /**
859 * AT+CRSM
860 * By using this command instead of Generic SIM Access +CSIM TE application
861 * has easier but more limited access to the SIM database.
862 *
863 * Command Possible response(s)
864 * +CRSM=<command>[,<fileid> +CRSM: <sw1>,<sw2>[,<response>]
865 * [,<P1>,<P2>,<P3>[,<data>[,<pathid>]]]] +CME ERROR: <err>
866 *
867 * <command>: (command passed on by the MT to the SIM; refer 3GPP TS 51.011 [28]):
868 * 176 READ BINARY
869 * 178 READ RECORD
870 * 192 GET RESPONSE
871 * 214 UPDATE BINARY
872 * 220 UPDATE RECORD
873 * 242 STATUS
874 * 203 RETRIEVE DATA
875 * 219 SET DATA
876 *
877 * <fileid>: integer type; this is the identifier of a elementary datafile on SIM.
878 * Mandatory for every command except STATUS.
879 *
880 * <P1>, <P2>, <P3>: integer type; parameters passed on by the MT to the SIM.
881 * These parameters are mandatory for every command,
882 * except GET RESPONSE and STATUS.
883 *
884 * <data>: information which shall be written to the SIM (hexadecimal character format).
885 *
886 * <pathid>: string type; contains the path of an elementary file on the SIM/UICC
887 * in hexadecimal format.
888 *
889 * <sw1>, <sw2>: integer type; information from the SIM about the execution of
890 * the actual command.
891 *
892 * <response>: response of a successful completion of the command previously issued
893 * (hexadecimal character format; refer +CSCS).
894 */
HandleSIM_IO(const Client & client,const std::string & command)895 void SimService::HandleSIM_IO(const Client& client,
896 const std::string& command) {
897 std::vector<std::string> kFileNotFoud = {"+CRSM: 106,130", "OK"};
898 std::vector<std::string> responses;
899
900 CommandParser cmd(command);
901 cmd.SkipPrefix(); // skip "AT+CRSM="
902
903 if (*cmd == "242,0,0,0,0") { // for cts teset
904 responses.push_back("+CRSM: 144,0,62338202782183023F00A50C80016187010183040007DBF08A01058B062F0601020002C60C90016083010183010A83010D8102FFFF");
905 responses.push_back("OK");
906 client.SendCommandResponse(responses);
907 return;
908 }
909
910 auto c = cmd.GetNextStrDeciToHex();
911 auto id = cmd.GetNextStrDeciToHex();
912 auto p1 = cmd.GetNextStrDeciToHex();
913 auto p2 = cmd.GetNextStrDeciToHex();
914 auto p3 = cmd.GetNextStrDeciToHex();
915
916 auto data = cmd.GetNextStr(',');
917 std::string path(cmd.GetNextStr());
918
919 XMLElement *root = sim_file_system_.GetRootElement();
920 if (!root) {
921 LOG(ERROR) << "Unable to find root element: IccProfile";
922 client.SendCommandResponse(kCmeErrorOperationNotAllowed);
923 return;
924 }
925
926 SimFileSystem::EFId fileid = (SimFileSystem::EFId)std::stoi(id, nullptr, 16);
927 if (path == "") {
928 path = SimFileSystem::GetUsimEFPath(fileid);
929 }
930 // EF_ADN under DF_PHONEBOOK is mapped to EF_ADN under DF_TELECOM per
931 // 3GPP TS 31.102 4.4.2
932 if (fileid == SimFileSystem::EF_ADN &&
933 path == SimFileSystem::GetUsimEFPath(fileid)) {
934 id = "4F3A";
935 path = MF_SIM + DF_TELECOM + DF_PHONEBOOK;
936 }
937
938 size_t pos = 0;
939 auto parent = root;
940 while (pos < path.length()) {
941 std::string sub_path(path.substr(pos, 4));
942 auto app = SimFileSystem::FindAttribute(parent, "path", sub_path);
943 if (!app) {
944 client.SendCommandResponse(kFileNotFoud);
945 return;
946 }
947 pos += 4;
948 parent = app;
949 }
950
951 XMLElement* ef = SimFileSystem::FindAttribute(parent, "id", id);
952 if (!ef) {
953 client.SendCommandResponse(kFileNotFoud);
954 return;
955 }
956
957 XMLElement *final = ef->FirstChildElement("SIMIO");
958 while (final) {
959 const XMLAttribute *attr_cmd = final->FindAttribute("cmd");
960 const XMLAttribute *attr_p1 = final->FindAttribute("p1");
961 const XMLAttribute *attr_p2 = final->FindAttribute("p2");
962 const XMLAttribute *attr_p3 = final->FindAttribute("p3");
963 const XMLAttribute *attr_data = final->FindAttribute("data");
964
965 if (c != "DC" && c != "D6") { // Except UPDATE RECORD or UPDATE BINARY
966 if ((attr_cmd && attr_cmd->Value() != c) ||
967 (attr_data && attr_data->Value() != data)) {
968 final = final->NextSiblingElement("SIMIO");
969 continue;
970 }
971 }
972 if (attr_p1 && attr_p1->Value() == p1 &&
973 attr_p2 && attr_p2->Value() == p2 &&
974 attr_p3 && attr_p3->Value() == p3) {
975 break;
976 }
977 final = final->NextSiblingElement("SIMIO");
978 }
979
980 if (!final) {
981 client.SendCommandResponse(kFileNotFoud);
982 return;
983 }
984
985 std::string response = "+CRSM: ";
986 if (c == "DC" || c == "D6") {
987 std::string temp = "144,0,";
988 temp += data;
989 final->SetText(temp.c_str());
990 sim_file_system_.doc.SaveFile(sim_file_system_.file_path.c_str());
991 response.append("144,0");
992 } else {
993 response.append(final->GetText());
994 }
995
996 responses.push_back(response);
997 responses.push_back("OK");
998 client.SendCommandResponse(responses);
999 }
1000
OnSimStatusChanged()1001 void SimService::OnSimStatusChanged() {
1002 auto ptr = network_service_;
1003 if (ptr) {
1004 ptr->OnSimStatusChanged(sim_status_);
1005 }
1006 }
1007
GetPhoneNumberElement()1008 XMLElement* SimService::GetPhoneNumberElement() {
1009 XMLElement* root = sim_file_system_.GetRootElement();
1010 if (!root) return nullptr;
1011
1012 auto path = SimFileSystem::GetUsimEFPath(SimFileSystem::EFId::EF_MSISDN);
1013
1014 size_t pos = 0;
1015 auto parent = root;
1016 while (pos < path.length()) {
1017 std::string sub_path(path.substr(pos, 4));
1018 auto app = SimFileSystem::FindAttribute(parent, "path", sub_path);
1019 if (!app) return nullptr;
1020 pos += 4;
1021 parent = app;
1022 }
1023
1024 XMLElement* ef = SimFileSystem::FindAttribute(parent, "id", "6F40");
1025 if (!ef) return nullptr;
1026
1027 return SimFileSystem::FindAttribute(ef, "cmd", "B2");
1028 }
1029
checkPin1AndAdjustSimStatus(std::string_view pin)1030 bool SimService::checkPin1AndAdjustSimStatus(std::string_view pin) {
1031 if (pin1_status_.VerifyPIN(pin) == true) {
1032 sim_status_ = SIM_STATUS_READY;
1033 OnSimStatusChanged();
1034 return true;
1035 }
1036
1037 if (pin1_status_.pin_remaining_times_ <= 0) {
1038 sim_status_ = SIM_STATUS_PUK;
1039 OnSimStatusChanged();
1040 }
1041
1042 return false;
1043 }
1044
1045 /* AT+CSIM */
HandleCSIM_IO(const Client & client,const std::string & command)1046 void SimService::HandleCSIM_IO(const Client& client,
1047 const std::string& command) {
1048 std::vector<std::string> responses;
1049
1050 CommandParser cmd(command);
1051 cmd.SkipPrefix(); // skip "AT+CSIM="
1052
1053 cmd.SkipComma();
1054 auto data = cmd.GetNextStr();
1055
1056 XMLElement *root = sim_file_system_.GetRootElement();
1057 if (!root) {
1058 LOG(ERROR) << "Unable to find root element: IccProfile";
1059 client.SendCommandResponse(kCmeErrorOperationNotAllowed);
1060 return;
1061 }
1062 // Get aid
1063 XMLElement* df = SimFileSystem::FindAttribute(root, "aid", "CSIM");
1064 if (!df) {
1065 client.SendCommandResponse(kCmeErrorNotFound);
1066 return;
1067 }
1068
1069 std::string data_value(data);
1070 if (data_value.length() > 10) { // for open channel with csim
1071 responses.push_back("+CSIM: 4,9000");
1072 responses.push_back("OK");
1073 client.SendCommandResponse(responses);
1074 return;
1075 }
1076 XMLElement* final = SimFileSystem::FindAttribute(df, "cmd", data_value);
1077 if (!final) {
1078 client.SendCommandResponse(kCmeErrorNotFound);
1079 return;
1080 }
1081
1082 auto id = data_value.substr(data_value.length() - 2, 2);
1083
1084 std::vector<LogicalChannel>::iterator iter = logical_channels_.begin();
1085 for (; iter != logical_channels_.end(); ++iter) {
1086 if (!iter->is_open) break;
1087 }
1088
1089 if (iter != logical_channels_.end() && iter->session_id ==stoi(id)) {
1090 iter->is_open = true;
1091 iter->df_name = "CSIM";
1092 }
1093
1094 std::stringstream ss;
1095 ss << "+CSIM: " << final->GetText();
1096
1097 responses.push_back(ss.str());
1098 responses.push_back("OK");
1099 client.SendCommandResponse(responses);
1100 }
1101
ChangePin1AndAdjustSimStatus(PinStatus::ChangeMode mode,std::string_view pin,std::string_view new_pin)1102 bool SimService::ChangePin1AndAdjustSimStatus(PinStatus::ChangeMode mode,
1103 std::string_view pin,
1104 std::string_view new_pin) {
1105 if (pin1_status_.ChangePIN(mode, pin, new_pin) == true) {
1106 sim_status_ = SIM_STATUS_READY;
1107 OnSimStatusChanged();
1108 return true;
1109 }
1110 if (sim_status_ == SIM_STATUS_READY && pin1_status_.pin_remaining_times_ <= 0) {
1111 sim_status_ = SIM_STATUS_PIN;
1112 OnSimStatusChanged();
1113 } else if (sim_status_ == SIM_STATUS_PIN && pin1_status_.puk_remaining_times_ <= 0) {
1114 sim_status_ = SIM_STATUS_ABSENT;
1115 OnSimStatusChanged();
1116 }
1117 return false;
1118 }
1119
HandleChangeOrEnterPIN(const Client & client,const std::string & command)1120 void SimService::HandleChangeOrEnterPIN(const Client& client,
1121 const std::string& command) {
1122 std::vector<std::string> responses;
1123
1124 CommandParser cmd(command);
1125 cmd.SkipPrefix(); // skip "AT+CPIN="
1126 switch (sim_status_) {
1127 case SIM_STATUS_ABSENT:
1128 responses.push_back(kCmeErrorSimNotInserted);
1129 break;
1130 case SIM_STATUS_NOT_READY:
1131 responses.push_back(kCmeErrorSimBusy);
1132 break;
1133 case SIM_STATUS_READY: {
1134 /*
1135 * this may be a request to change the PIN with pin and new pin:
1136 * AT+CPIN=pin,newpin
1137 * or a request to enter the PIN2
1138 * AT+CPIN=pin2
1139 */
1140 auto pos = cmd->find(',');
1141 if (pos != std::string_view::npos) { // change pin with new pin
1142 auto pin = cmd.GetNextStr(',');
1143 auto new_pin = *cmd;
1144
1145 if (ChangePin1AndAdjustSimStatus(PinStatus::WITH_PIN, pin, new_pin)) {
1146 responses.push_back("OK");
1147 } else {
1148 responses.push_back(kCmeErrorIncorrectPassword); /* incorrect PIN */
1149 }
1150 } else { // verify pin2
1151 if (pin2_status_.VerifyPIN(*cmd) == true) {
1152 responses.push_back("OK");
1153 } else {
1154 responses.push_back(kCmeErrorIncorrectPassword); /* incorrect PIN2 */
1155 }
1156 }
1157 break;
1158 }
1159 case SIM_STATUS_PIN: { /* waiting for PIN */
1160 if (checkPin1AndAdjustSimStatus(*cmd) == true) {
1161 responses.push_back("OK");
1162 } else {
1163 responses.push_back(kCmeErrorIncorrectPassword);
1164 }
1165 break;
1166 }
1167 case SIM_STATUS_PUK: {
1168 /*
1169 * this may be a request to unlock the puk with new pin:
1170 * AT+CPIN=puk,newpin
1171 */
1172 auto pos = cmd->find(',');
1173 if (pos != std::string_view::npos) {
1174 auto puk = cmd.GetNextStr(',');
1175 auto new_pin = *cmd;
1176 if (ChangePin1AndAdjustSimStatus(PinStatus::WITH_PUK, puk, new_pin)) {
1177 responses.push_back("OK");
1178 } else {
1179 responses.push_back(kCmeErrorIncorrectPassword);
1180 }
1181 } else {
1182 responses.push_back(kCmeErrorOperationNotAllowed);
1183 }
1184 break;
1185 }
1186 default:
1187 responses.push_back(kCmeErrorOperationNotAllowed);
1188 break;
1189 }
1190
1191 client.SendCommandResponse(responses);
1192 }
1193
1194 /**
1195 * AT+CIMI
1196 * Execution command causes the TA to return <IMSI>, which is intended to
1197 * permit the TE to identify the individual SIM card or active application in
1198 * the UICC (GSM or USIM) which is attached to MT.
1199 *
1200 * Command Possible response(s)
1201 * +CIMI <IMSI>
1202 * +CME ERROR: <err>
1203 *
1204 * <IMSI>: International Mobile Subscriber Identity (string without double quotes)
1205 *
1206 * see RIL_REQUEST_GET_IMSI in RIL
1207 */
HandleGetIMSI(const Client & client)1208 void SimService::HandleGetIMSI(const Client& client) {
1209 std::vector<std::string> responses;
1210
1211 XMLElement *root = sim_file_system_.GetRootElement();
1212 if (!root) {
1213 client.SendCommandResponse(kCmeErrorOperationNotAllowed);
1214 return;
1215 }
1216
1217 XMLElement* mf = SimFileSystem::FindAttribute(root, "path", MF_SIM);
1218 if (!mf) {
1219 client.SendCommandResponse(kCmeErrorNotFound);
1220 return;
1221 }
1222
1223 XMLElement* df = SimFileSystem::FindAttribute(mf, "path", DF_ADF);
1224 if (!df) {
1225 client.SendCommandResponse(kCmeErrorNotFound);
1226 return;
1227 }
1228
1229 XMLElement* ef = SimFileSystem::FindAttribute(df, "id", "6F07");
1230 if (!ef) {
1231 client.SendCommandResponse(kCmeErrorNotFound);
1232 return;
1233 }
1234
1235 XMLElement *final = ef->FirstChildElement("CIMI");
1236 if (!final) {
1237 client.SendCommandResponse(kCmeErrorNotFound);
1238 return;
1239 }
1240
1241 responses.push_back(final->GetText());
1242 responses.push_back("OK");
1243 client.SendCommandResponse(responses);
1244 }
1245
1246 /**
1247 * AT+CICCID
1248 * Integrated Circuit Card IDentifier (ICCID) is Unique Identifier of the SIM CARD.
1249 * File is located in the SIM card at EFiccid (0x2FE2).
1250 *
1251 * see RIL_REQUEST_GET_SIM_STATUS in RIL
1252 */
HandleGetIccId(const Client & client)1253 void SimService::HandleGetIccId(const Client& client) {
1254 std::vector<std::string> responses;
1255
1256 XMLElement *root = sim_file_system_.GetRootElement();
1257 if (!root) {
1258 client.SendCommandResponse(kCmeErrorOperationNotAllowed);
1259 return;
1260 }
1261
1262 XMLElement* mf = SimFileSystem::FindAttribute(root, "path", MF_SIM);
1263 if (!mf) {
1264 client.SendCommandResponse(kCmeErrorNotFound);
1265 return;
1266 }
1267
1268 XMLElement* ef = SimFileSystem::FindAttribute(mf, "id", "2FE2");
1269 if (!ef) {
1270 client.SendCommandResponse(kCmeErrorNotFound);
1271 return;
1272 }
1273
1274 XMLElement *final = ef->FirstChildElement("CCID");
1275 if (!final) {
1276 client.SendCommandResponse(kCmeErrorNotFound);
1277 return;
1278 }
1279
1280 responses.push_back(final->GetText());
1281 responses.push_back("OK");
1282 client.SendCommandResponse(responses);
1283 }
1284
1285 /*
1286 * AT+CLCK
1287 * Execute command is used to lock, unlock or interrogate a MT or a network
1288 * facility <fac>.
1289 *
1290 * Command Possible response(s)
1291 * +CLCK=<fac>, <mode> [, <password> OK or +CME ERROR: <err>
1292 * [, <class>]] +CLCK: <status>[,<class1>[<CR><LF>+CLCK:
1293 * <status>,<class2>[...]](when mode=2,it’s
1294 * in inquiry status.)
1295 * <fac> values reserved by the present document:
1296 * "SC": SIM (lock SIM/UICC card installed in the currently selected card
1297 * slot) (SIM/UICC asks password in MT power‑up and when this lock
1298 * command issued).
1299 * "FD": SIM card or active application in the UICC (GSM or USIM) fixed
1300 * dialling memory feature (if PIN2 authentication has not been done
1301 * during the current session, PIN2 is required as <passwd>).
1302 * <mode>: integer type
1303 * 0: unlock
1304 * 1: lock
1305 * 2: query status
1306 * <status>: integer type
1307 * 0: not active
1308 * 1: active
1309 * <passwd>: string type; shall be the same as password specified for the
1310 * facility from the MT user interface or with command
1311 * Change Password +CPWD.
1312 * <classx> is a sum of integers each representing a class of information
1313 * (default 7 - voice, data and fax):
1314 * 1 voice (telephony)
1315 * 2 data
1316 * 4 fax (facsimile services)
1317 * 8 short message service
1318 * 16 data circuit sync
1319 * 32 data circuit async
1320 * 64 dedicated packet access
1321 * 128 dedicated PAD access
1322 *
1323 * see RIL_REQUEST_SET_FACILITY_LOCK in RIL
1324 */
HandleFacilityLock(const Client & client,const std::string & command)1325 void SimService::HandleFacilityLock(const Client& client,
1326 const std::string& command) {
1327 CommandParser cmd(command);
1328 std::string lock(cmd.GetNextStr());
1329 int mode = cmd.GetNextInt();
1330 auto password = cmd.GetNextStr();
1331 // Ignore class from RIL
1332
1333 auto iter = facility_lock_.find(lock);
1334 if (iter == facility_lock_.end()) {
1335 client.SendCommandResponse(kCmeErrorOperationNotSupported);
1336 return;
1337 }
1338
1339 std::stringstream ss;
1340 std::vector<std::string> responses;
1341 switch (mode) {
1342 case FacilityLock::Mode::QUERY: {
1343 ss << "+CLCK: " << iter->second.lock_status;
1344 responses.push_back(ss.str());
1345 responses.push_back("OK");
1346 break;
1347 }
1348 case FacilityLock::Mode::LOCK:
1349 case FacilityLock::Mode::UNLOCK: {
1350 if (lock == "SC") {
1351 if (checkPin1AndAdjustSimStatus(password) == true) {
1352 iter->second.lock_status = (FacilityLock::LockStatus)mode;
1353 responses.push_back("OK");
1354 } else {
1355 responses.push_back(kCmeErrorIncorrectPassword);
1356 }
1357 } else if (lock == "FD") {
1358 if (pin2_status_.VerifyPIN(password) == true) {
1359 iter->second.lock_status = (FacilityLock::LockStatus)mode;
1360 responses.push_back("OK");
1361 } else {
1362 responses.push_back(kCmeErrorIncorrectPassword);
1363 }
1364 } else { // Don't need password except 'SC' and 'FD'
1365 iter->second.lock_status = (FacilityLock::LockStatus)mode;
1366 responses.push_back("OK");
1367 }
1368 break;
1369 }
1370 default:
1371 responses.push_back(kCmeErrorInCorrectParameters);
1372 break;
1373 }
1374
1375 client.SendCommandResponse(responses);
1376 }
1377
1378 /**
1379 * AT+CCHO
1380 * The currently selected UICC will open a new logical channel; select the
1381 * application identified by the <dfname> received with this command and return
1382 * a session Id as the response.
1383 *
1384 * Command Possible response(s)
1385 * +CCHO=<dfname> <sessionid>
1386 * +CME ERROR: <err>
1387 *
1388 * <dfname>: all selectable applications in the UICC are referenced by a DF
1389 * name coded on 1 to 16 bytes.
1390 * <sessionid>: integer type; a session Id to be used in order to target a
1391 * specific application on the smart card (e.g. (U)SIM, WIM, ISIM)
1392 * using logical channels mechanism.
1393 *
1394 * see RIL_REQUEST_SIM_OPEN_CHANNEL in RIL
1395 */
HandleOpenLogicalChannel(const Client & client,const std::string & command)1396 void SimService::HandleOpenLogicalChannel(const Client& client,
1397 const std::string& command) {
1398 std::vector<std::string> responses;
1399
1400 CommandParser cmd(command);
1401 cmd.SkipPrefix(); // skip AT+CCHO=
1402 if (cmd->empty()) {
1403 client.SendCommandResponse(kCmeErrorInCorrectParameters);
1404 return;
1405 }
1406
1407 XMLElement *root = sim_file_system_.GetRootElement();
1408 if (!root) {
1409 client.SendCommandResponse(kCmeErrorOperationNotAllowed);
1410 return;
1411 }
1412
1413 std::string aid_value(*cmd);
1414 XMLElement* df = SimFileSystem::FindAttribute(root, "aid", aid_value);
1415 if (!df) {
1416 client.SendCommandResponse(kCmeErrorNotFound);
1417 return;
1418 }
1419
1420 std::vector<LogicalChannel>::iterator iter = logical_channels_.begin();
1421 for (; iter != logical_channels_.end(); ++iter) {
1422 if (!iter->is_open) break;
1423 }
1424
1425 if (iter != logical_channels_.end()) {
1426 iter->is_open = true;
1427 iter->df_name = *cmd;
1428
1429 std::stringstream ss;
1430 ss << iter->session_id;
1431 responses.push_back(ss.str());
1432 responses.push_back("OK");
1433 } else {
1434 responses.push_back(kCmeErrorMemoryFull);
1435 }
1436
1437 client.SendCommandResponse(responses);
1438 }
1439
1440 /**
1441 * AT+CCHC
1442 * This command asks the ME to close a communication session with the active
1443 * UICC.
1444 *
1445 * Command Possible response(s)
1446 * +CCHC=<sessionid> +CCHC
1447 * +CME ERROR: <err>
1448 * <sessionid>: see AT+CCHO
1449 *
1450 * see RIL_REQUEST_SIM_CLOSE_CHANNEL in RIL
1451 */
HandleCloseLogicalChannel(const Client & client,const std::string & command)1452 void SimService::HandleCloseLogicalChannel(const Client& client,
1453 const std::string& command) {
1454 std::vector<std::string> responses;
1455
1456 CommandParser cmd(command);
1457 cmd.SkipPrefix(); // skip AT+CCHC=
1458
1459 int session_id = cmd.GetNextInt();
1460 std::vector<LogicalChannel>::iterator iter = logical_channels_.begin();
1461 for (; iter != logical_channels_.end(); ++iter) {
1462 if (iter->session_id == session_id) break;
1463 }
1464
1465 if (iter != logical_channels_.end() && iter->is_open) {
1466 iter->is_open = false;
1467 iter->df_name.clear();
1468 responses.push_back("+CCHC");
1469 responses.push_back("OK");
1470 } else {
1471 responses.push_back(kCmeErrorNotFound);
1472 }
1473 client.SendCommandResponse(responses);
1474 }
1475
1476 /**
1477 * AT+CGLA
1478 * Set command transmits to the MT the <command> it then shall send as it is
1479 * to the selected UICC. In the same manner the UICC <response> shall be sent
1480 * back by the MT to the TA as it is.
1481 *
1482 * Command Possible response(s)
1483 * +CGLA=<sessionid>,<length>, +CGLA: <length>,<response>
1484 * +CME ERROR: <err>
1485 * <sessionid>: AT+CCHO
1486 * <length>: integer type; length of the characters that are sent to TE in
1487 * <command> or <response> .
1488 * <command>: command passed on by the MT to the UICC in the format as described
1489 * in 3GPP TS 31.101 [65] (hexadecimal character format; refer +CSCS).
1490 * <response>: response to the command passed on by the UICC to the MT in the
1491 * format as described in 3GPP TS 31.101 [65] (hexadecimal character
1492 * format; refer +CSCS).
1493 *
1494 * see RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL in RIL
1495 */
HandleTransmitLogicalChannel(const Client & client,const std::string & command)1496 void SimService::HandleTransmitLogicalChannel(const Client& client,
1497 const std::string& command) {
1498 std::vector<std::string> responses;
1499
1500 CommandParser cmd(command);
1501 cmd.SkipPrefix(); // skip AT+CGLA=
1502
1503 int session_id = cmd.GetNextInt();
1504 int length = cmd.GetNextInt();
1505 if (cmd->length() != length) {
1506 client.SendCommandResponse(kCmeErrorInCorrectParameters);
1507 return;
1508 }
1509
1510 // Check if session id is opened
1511 auto iter = logical_channels_.begin();
1512 for (; iter != logical_channels_.end(); ++iter) {
1513 if (iter->session_id == session_id && iter->is_open) {
1514 break;
1515 }
1516 }
1517
1518 if (iter == logical_channels_.end()) {
1519 client.SendCommandResponse(kCmeErrorInvalidIndex);
1520 return;
1521 }
1522
1523 XMLElement *root = sim_file_system_.GetRootElement();
1524 if (!root) {
1525 client.SendCommandResponse(kCmeErrorOperationNotAllowed);
1526 return;
1527 }
1528
1529 // Get aid
1530 XMLElement* df = SimFileSystem::FindAttribute(root, "aid", iter->df_name);
1531 if (!df) {
1532 client.SendCommandResponse(kCmeErrorNotFound);
1533 return;
1534 }
1535
1536 if (iter->df_name != "CSIM") {
1537 std::string command_vaule(*cmd);
1538 if (command_vaule.substr(2, 2) == "a4") {
1539 last_file_id_ = command_vaule.substr(command_vaule.length() - 4, 4);
1540 }
1541 df = SimFileSystem::FindAttribute(df, "id", last_file_id_);
1542 if (!df) {
1543 client.SendCommandResponse(kCmeErrorNotFound);
1544 return;
1545 }
1546 }
1547
1548 std::string attr_value(*cmd);
1549 XMLElement* final = SimFileSystem::FindAttribute(df, "cmd", attr_value);
1550 if (!final) {
1551 client.SendCommandResponse(kCmeErrorNotFound);
1552 return;
1553 }
1554
1555 std::stringstream ss;
1556 ss << "+CGLA: " << final->GetText();
1557 responses.push_back(ss.str());
1558 responses.push_back("OK");
1559 client.SendCommandResponse(responses);
1560 }
1561
1562 /**
1563 * AT+CPWD
1564 * Action command sets a new password for the facility lock function defined
1565 * by command Facility Lock +CLCK
1566 *
1567 * Command Possible response(s)
1568 * +CPWD=<fac>,<oldpwd>,<newpwd> +CME ERROR: <err>
1569 *
1570 * <fac>:
1571 * "P2" SIM PIN2
1572 * refer Facility Lock +CLCK for other values
1573 * <oldpwd>, <newpwd>:
1574 * string type; <oldpwd> shall be the same as password specified for the
1575 * facility from the MT user interface or with command Change Password +CPWD
1576 * and <newpwd> is the new password; maximum length of password can be determined
1577 * with <pwdlength>
1578 * <pwdlength>: integer type maximum length of the password for the facility
1579 */
HandleChangePassword(const Client & client,const std::string & command)1580 void SimService::HandleChangePassword(const Client& client,
1581 const std::string& command) {
1582 std::string response = kCmeErrorIncorrectPassword;
1583
1584 CommandParser cmd(command);
1585 cmd.SkipPrefix();
1586 auto lock = cmd.GetNextStr();
1587 auto old_password = cmd.GetNextStr();
1588 auto new_password = cmd.GetNextStr();
1589
1590 if (lock == "SC") {
1591 if (ChangePin1AndAdjustSimStatus(PinStatus::WITH_PIN, old_password, new_password)) {
1592 response = "OK";
1593 }
1594 } else if (lock == "P2" || lock == "FD") {
1595 if (pin2_status_.ChangePIN(PinStatus::WITH_PIN, old_password, new_password)) {
1596 response = "OK";
1597 }
1598 } else {
1599 response = kCmeErrorOperationNotSupported;;
1600 }
1601
1602 client.SendCommandResponse(response);
1603 }
1604
1605 /**
1606 * AT+CPINR
1607 * Execution command cause the MT to return the number of remaining PIN retries
1608 * for the MT passwords with intermediate result code
1609 *
1610 * Command Possible response(s)
1611 * +CPINR[=<sel_code>] +CPINR: <code>,<retries>[,<default_retries>]
1612 *
1613 * <retries>:
1614 * integer type. Number of remaining retries per PIN.
1615 * <default_retries>:
1616 * integer type. Number of default/initial retries per PIN.
1617 * <code>:
1618 * Type of PIN. All values listed under the description of the AT+CPIN command
1619 * <sel_code>: String type. Same values as for the <code> and <ext_code> parameters.
1620 * these values are strings and shall be indicated within double quotes.
1621 */
HandleQueryRemainTimes(const Client & client,const std::string & command)1622 void SimService::HandleQueryRemainTimes(const Client& client,
1623 const std::string& command) {
1624 std::vector<std::string> responses;
1625 std::stringstream ss;
1626
1627 CommandParser cmd(command);
1628 cmd.SkipPrefix();
1629 auto lock_type = cmd.GetNextStr();
1630
1631 if (lock_type == "SIM PIN") {
1632 ss << "+CPINR: SIM PIN," << pin1_status_.pin_remaining_times_ << ","
1633 << kSimPinMaxRetryTimes;
1634 } else if (lock_type == "SIM PUK") {
1635 ss << "+CPINR: SIM PUK," << pin1_status_.puk_remaining_times_ << ","
1636 << kSimPukMaxRetryTimes;
1637 } else if (lock_type == "SIM PIN2") {
1638 ss << "+CPINR: SIM PIN2," << pin2_status_.pin_remaining_times_ << ","
1639 << kSimPinMaxRetryTimes;
1640 } else if (lock_type == "SIM PUK2") {
1641 ss << "+CPINR: SIM PUK2," << pin2_status_.puk_remaining_times_ << ","
1642 << kSimPukMaxRetryTimes;
1643 } else {
1644 responses.push_back(kCmeErrorInCorrectParameters);
1645 client.SendCommandResponse(responses);
1646 return;
1647 }
1648
1649 responses.push_back(ss.str());
1650 responses.push_back("OK");
1651 client.SendCommandResponse(responses);
1652 }
1653
1654 /**
1655 * see
1656 * RIL_REQUEST_CDMA_SET_SUBSCRIPTION or
1657 * RIL_REQUEST_CDMA_GET_SUBSCRIPTION in RIL
1658 */
HandleCdmaSubscriptionSource(const Client & client,const std::string & command)1659 void SimService::HandleCdmaSubscriptionSource(const Client& client,
1660 const std::string& command) {
1661 std::vector<std::string> responses;
1662
1663 CommandParser cmd(command);
1664 if (*cmd == "AT+CCSS?") { // Query
1665 std::stringstream ss;
1666 ss << "+CCSS: " << cdma_subscription_source_;
1667 responses.push_back(ss.str());
1668 } else { // Set
1669 cdma_subscription_source_ = cmd.GetNextInt();
1670 }
1671 responses.push_back("OK");
1672 client.SendCommandResponse(responses);
1673 }
1674
1675 /**
1676 * see
1677 * RIL_REQUEST_CDMA_SET_ROAMNING_PREFERENCE or
1678 * RIL_REQUEST_CDMA_GET_ROAMNING_PREFERENCE in RIL
1679 */
HandleCdmaRoamingPreference(const Client & client,const std::string & command)1680 void SimService::HandleCdmaRoamingPreference(const Client& client,
1681 const std::string& command) {
1682 std::vector<std::string> responses;
1683
1684 CommandParser cmd(command);
1685 if (*cmd == "AT+WRMP?") { // Query
1686 std::stringstream ss;
1687 ss << "+WRMP: " << cdma_roaming_preference_;
1688 responses.push_back(ss.str());
1689 } else { // Set
1690 cdma_roaming_preference_ = cmd.GetNextInt();
1691 }
1692 responses.push_back("OK");
1693 client.SendCommandResponse(responses);
1694 }
1695
HandleSimAuthentication(const Client & client,const std::string & command)1696 void SimService::HandleSimAuthentication(const Client& client,
1697 const std::string& command) {
1698 std::vector<std::string> responses;
1699
1700 CommandParser cmd(command);
1701 cmd.SkipPrefix();
1702
1703 // Input format: ^MBAU=<RAND>[,<AUTN>]
1704 auto cmds = cmd.GetNextStr();
1705 // Output format: ^MBAU: <STATUS>[,<KC>,<SRES>][,<CK>,<IK>,<RES/AUTS>]
1706 std::stringstream ss;
1707
1708 // Authentication challenges done in CTS.
1709 if (cmds == "2713AB0BA8E8E7D8F1D74545BA03F563") {
1710 // CarrierApiTest#testGetIccAuthentication (base64Challenge)
1711 ss << "^MBAU: 0,8F2980FC3872FF89,E9620240";
1712 } else if (cmds == "C3718EC16B3C2A66F8A7200A64069F04") {
1713 // CarrierApiTest#testGetIccAuthentication (base64Challenge2)
1714 ss << "^MBAU: 0,CFDA6C980502DA48,F7E53577";
1715 } else if (cmds == "11111111111111111111111111111111") {
1716 // CarrierApiTest#testEapSimAuthentication
1717 ss << "^MBAU: 0,0000000000000000,00000000";
1718 } else if (cmds == "11111111111111111111111111111111,12351417161900001130131215141716") {
1719 // CarrierApiTest#testEapAkaAuthentication
1720 // Note: the "DB" prefix gets appended where the RIL parses this response.
1721 ss << "^MBAU: 0,111013121514171619181B1A1D1C1F1E,1013121514171619181B1A1D1C1F1E11,"
1722 "13121514171619181B1A1D1C1F1E1110";
1723 }
1724
1725 responses.push_back(ss.str());
1726 responses.push_back("OK");
1727 client.SendCommandResponse(responses);
1728 }
1729
HandlePhoneNumberUpdate(const Client & client,const std::string & command)1730 void SimService::HandlePhoneNumberUpdate(const Client& client,
1731 const std::string& command) {
1732 (void)client;
1733 CommandParser cmd(command);
1734 cmd.SkipWhiteSpace();
1735 SetPhoneNumber(cmd.GetNextStr(' '));
1736 }
1737
1738 } // namespace cuttlefish
1739