• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "map_mse_instance.h"
17 #include "adapter_config.h"
18 #include "btm.h"
19 #include "map_mse_server.h"
20 #include "map_mse_service.h"
21 
22 namespace OHOS {
23 namespace bluetooth {
24 struct MapMseInstance::impl {
25     class ConnectObserver : public MseObserver {
26     public:
27         /**
28          * @brief Construct a new Connect Observer object
29          *
30          * @param masInstance Reference to the Mas instance
31          */
32         explicit ConnectObserver(MapMseInstance &masInstance);
33 
34         /**
35          * @brief A destructor used to delete the Connect Observer object.
36          *
37          */
38         virtual ~ConnectObserver() = default;
39 
40     private:
41         /**
42          * @brief The function is called when new MCE connection available
43          *
44          * @param session Reference to the ObexServerSession Value
45          */
46         void OnConnected(ObexServerSession &session) override;
47 
48         /**
49          * @brief The function is called when MCE connect is incoming
50          *
51          * @param incomingConnect Reference to the ObexIncomingConnect Value
52          */
53         void OnIncomingConnect(ObexIncomingConnect &incomingConnect) override;
54 
55         /**
56          * @brief The function is called when MCE transport disconnect is incoming
57          *
58          * @param remoteAddr Remote Bluetooth address
59          */
60         void OnTransportDisconnected(const RawAddress &remoteAddr) override;
61 
62         /**
63          * @brief The function is called when MCE Disconnect is incoming
64          *
65          * @param remoteAddr Remote Bluetooth address
66          */
67         void OnDisconnect(const RawAddress &remoteAddr) override;
68 
69         /**
70          * @brief The function is called when Obex busy or not busy
71          *
72          * @param remoteAddr Remote Bluetooth address
73          * @param isBusy true:busy false:not busy
74          */
75         void OnBusy(const RawAddress &remoteAddr, bool isBusy) override;
76 
77         /**
78          * @brief Permission handle for incoming connection
79          *
80          * @param incomingConnect Reference to the ObexIncomingConnect Value
81          */
82         void PermissionHandle(ObexIncomingConnect &incomingConnect);
83 
84         MapMseInstance &masInstance_;
85 
86         BT_DISALLOW_COPY_AND_ASSIGN(ConnectObserver);
87     };
88     std::unique_ptr<MapMseServer> mseServer_ = nullptr;
89     std::unique_ptr<MapMseResource> content_ = nullptr;
90     std::unique_ptr<ConnectObserver> connectObserver_ = nullptr;
91     std::unordered_map<std::string, ObexIncomingConnect *> obexIncomingMap_ {};
92     std::unordered_map<std::string, ObexServerSession *> obexSessionMap_ {};
93 };
94 
MapMseInstance(utility::Dispatcher & dispatcher,uint8_t masId,uint16_t l2capPsm,const MapAccountItem & accountItem,bool smsSupport)95 MapMseInstance::MapMseInstance(utility::Dispatcher &dispatcher, uint8_t masId, uint16_t l2capPsm,
96     const MapAccountItem &accountItem, bool smsSupport)
97     : dispatcher_(dispatcher),
98       masInstanceId_(masId),
99       goepL2capPsm_(l2capPsm),
100       accountItem_(accountItem),
101       smsSupport_(smsSupport),
102       pimpl(std::make_unique<impl>())
103 {
104     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
105 
106     pimpl->connectObserver_ = std::make_unique<MapMseInstance::impl::ConnectObserver>(*this);
107     shutDownEnable_ = false;
108 }
109 
MapMseInstance(utility::Dispatcher & dispatcher,uint8_t masId,uint16_t l2capPsm,bool smsSupport)110 MapMseInstance::MapMseInstance(utility::Dispatcher &dispatcher, uint8_t masId, uint16_t l2capPsm, bool smsSupport)
111     : dispatcher_(dispatcher),
112       masInstanceId_(masId),
113       goepL2capPsm_(l2capPsm),
114       smsSupport_(smsSupport),
115       pimpl(std::make_unique<impl>())
116 {
117     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
118 
119     accountItem_ = MapAccountItem();
120     pimpl->connectObserver_ = std::make_unique<MapMseInstance::impl::ConnectObserver>(*this);
121     shutDownEnable_ = false;
122 }
123 
~MapMseInstance()124 MapMseInstance::~MapMseInstance()
125 {
126     stateMap_.clear();
127     nativeMap_.clear();
128     pimpl->obexIncomingMap_.clear();
129     pimpl->obexSessionMap_.clear();
130 }
131 
RegistMapObserver(MapObserver & observer)132 int MapMseInstance::RegistMapObserver(MapObserver &observer)
133 {
134     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
135 
136     mapObserver_ = &observer;
137     return Result::SUCCEED;
138 }
139 
DeregisterObserver(MapObserver & observer)140 void MapMseInstance::DeregisterObserver(MapObserver &observer)
141 {
142     mapObserver_ = nullptr;
143 }
144 
NativeData(MapMseInstance & masInstance)145 MapMseInstance::NativeData::NativeData(MapMseInstance &masInstance) : masInstance_(masInstance)
146 {
147     MSE_LOG_INFO("%{public}s Create", __PRETTY_FUNCTION__);
148 }
149 
StartTimer(std::function<void ()> callback,int ms)150 bool MapMseInstance::NativeData::StartTimer(std::function<void()> callback, int ms)
151 {
152     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
153 
154     timer_ = std::make_unique<utility::Timer>(callback);
155     return timer_->Start(ms, false);
156 }
157 
StopTimer()158 void MapMseInstance::NativeData::StopTimer()
159 {
160     if (timer_) {
161         MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
162         timer_->Stop();
163         timer_ = nullptr;
164     }
165 }
166 
ConnectObserver(MapMseInstance & masInstance)167 MapMseInstance::impl::ConnectObserver::ConnectObserver(MapMseInstance &masInstance) : masInstance_(masInstance)
168 {
169     MSE_LOG_INFO("%{public}s Create", __PRETTY_FUNCTION__);
170 }
171 
OnConnected(ObexServerSession & session)172 void MapMseInstance::impl::ConnectObserver::OnConnected(ObexServerSession &session)
173 {
174     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
175 
176     std::string remoteAddr = session.GetRemoteAddr().GetAddress();
177     {
178         std::lock_guard<std::recursive_mutex> lock(masInstance_.instanceMapMutex_);
179         if (masInstance_.stateMap_.find(remoteAddr) != masInstance_.stateMap_.end()) {
180             masInstance_.stateMap_[remoteAddr] = BTConnectState::CONNECTED;
181         }
182         if (masInstance_.pimpl->obexSessionMap_.find(remoteAddr) == masInstance_.pimpl->obexSessionMap_.end()) {
183             masInstance_.pimpl->obexSessionMap_[remoteAddr] = &session;
184         }
185         if (auto iter = masInstance_.nativeMap_.find(remoteAddr); iter != masInstance_.nativeMap_.end()) {
186             masInstance_.nativeMap_[remoteAddr]->IsAccepted = false;
187         }
188     }
189     if (masInstance_.mapObserver_) {
190         masInstance_.mapObserver_->OnConnectionStateChanged(
191             remoteAddr, masInstance_.masInstanceId_, BTConnectState::CONNECTED);
192     }
193 }
194 
OnIncomingConnect(ObexIncomingConnect & incomingConnect)195 void MapMseInstance::impl::ConnectObserver::OnIncomingConnect(ObexIncomingConnect &incomingConnect)
196 {
197     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
198 
199     RawAddress rawAddr = incomingConnect.GetRemoteAddress();
200     auto addr = rawAddr.GetAddress();
201     if (masInstance_.shutDownEnable_) {
202         MSE_LOG_ERROR("Connection denied during service shutdown.");
203         incomingConnect.RejectConnection();
204         return;
205     }
206     {
207         std::lock_guard<std::recursive_mutex> lock(masInstance_.instanceMapMutex_);
208         if (masInstance_.nativeMap_.find(addr) == masInstance_.nativeMap_.end()) {
209             masInstance_.nativeMap_[addr] = std::move(std::make_unique<NativeData>(masInstance_));
210         }
211         if (masInstance_.stateMap_.find(addr) == masInstance_.stateMap_.end()) {
212             masInstance_.stateMap_[addr] = BTConnectState::DISCONNECTED;
213         }
214         if (masInstance_.stateMap_[addr] == BTConnectState::DISCONNECTING) {
215             MSE_LOG_ERROR("Connection denied while disconnected.");
216             incomingConnect.RejectConnection();
217             return;
218         }
219     }
220     if (masInstance_.mapObserver_) {
221         masInstance_.mapObserver_->OnConnectionStateChanged(
222             rawAddr, masInstance_.masInstanceId_, BTConnectState::CONNECTING);
223     }
224     PermissionHandle(incomingConnect);
225 }
226 
PermissionHandle(ObexIncomingConnect & incomingConnect)227 void MapMseInstance::impl::ConnectObserver::PermissionHandle(ObexIncomingConnect &incomingConnect)
228 {
229     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
230 
231     std::lock_guard<std::recursive_mutex> lock(masInstance_.instanceMapMutex_);
232     RawAddress rawAddr = incomingConnect.GetRemoteAddress();
233     auto addr = rawAddr.GetAddress();
234     masInstance_.stateMap_[addr] = BTConnectState::CONNECTING;
235     BTPermissionType permission = AdapterManager::GetInstance()->GetMessagePermission(rawAddr.GetAddress());
236     if (BTPermissionType::ACCESS_UNKNOWN == permission) {
237         masInstance_.pimpl->obexIncomingMap_[addr] = &incomingConnect;
238         masInstance_.nativeMap_[addr]->IncomingStartTimer(rawAddr);
239         if (masInstance_.mapObserver_) {
240             masInstance_.mapObserver_->OnIncomingConnect(rawAddr, masInstance_.masInstanceId_);
241         }
242     } else if (BTPermissionType::ACCESS_ALLOWED == permission) {
243         masInstance_.nativeMap_[addr]->StopTimer();
244         incomingConnect.AcceptConnection();
245         masInstance_.nativeMap_[addr]->IsAccepted = true;
246         if (masInstance_.mapObserver_) {
247             masInstance_.mapObserver_->OnTransportConnected(rawAddr, masInstance_.masInstanceId_);
248         }
249     } else if (BTPermissionType::ACCESS_FORBIDDEN == permission) {
250         masInstance_.nativeMap_[addr]->StopTimer();
251         incomingConnect.RejectConnection();
252         masInstance_.nativeMap_[addr]->IsAccepted = false;
253         masInstance_.stateMap_[addr] = BTConnectState::DISCONNECTED;
254         if (masInstance_.mapObserver_) {
255             masInstance_.mapObserver_->OnRejectConnection(rawAddr, masInstance_.masInstanceId_);
256         }
257     }
258 }
259 
IncomingStartTimer(const RawAddress & rawAddr)260 void MapMseInstance::NativeData::IncomingStartTimer(const RawAddress &rawAddr)
261 {
262     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
263 
264     StartTimer(std::bind(&MapMseInstance::NativeData::IncomingTimeout, this, rawAddr), MAP_MSE_INCOMING_TIME_OUT);
265 }
266 
IncomingTimeout(const RawAddress & rawAddr)267 void MapMseInstance::NativeData::IncomingTimeout(const RawAddress &rawAddr)
268 {
269     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
270 
271     masInstance_.dispatcher_.PostTask(std::bind(&MapMseInstance::NativeData::ProcessIncomingTimeout, this, rawAddr));
272 }
273 
ProcessIncomingTimeout(const RawAddress & rawAddr)274 void MapMseInstance::NativeData::ProcessIncomingTimeout(const RawAddress &rawAddr)
275 {
276     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
277 
278     std::string addr = rawAddr.GetAddress();
279     if (masInstance_.pimpl->obexIncomingMap_.find(addr) != masInstance_.pimpl->obexIncomingMap_.end()) {
280         masInstance_.pimpl->obexIncomingMap_[addr]->RejectConnection();
281         IsAccepted = false;
282         if (masInstance_.mapObserver_) {
283             masInstance_.SetConnectState(addr, BTConnectState::DISCONNECTED);
284             masInstance_.mapObserver_->OnIncomingTimeout(rawAddr, masInstance_.masInstanceId_);
285         }
286     }
287     if (auto iter = masInstance_.pimpl->obexIncomingMap_.find(addr);
288         iter != masInstance_.pimpl->obexIncomingMap_.end()) {
289         masInstance_.pimpl->obexIncomingMap_.erase(iter);
290     }
291 }
292 
OnTransportDisconnected(const RawAddress & remoteAddr)293 void MapMseInstance::impl::ConnectObserver::OnTransportDisconnected(const RawAddress &remoteAddr)
294 {
295     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
296 
297     auto addr = remoteAddr.GetAddress();
298     {
299         std::lock_guard<std::recursive_mutex> lock(masInstance_.instanceMapMutex_);
300         if (auto iter = masInstance_.pimpl->obexSessionMap_.find(addr);
301             iter != masInstance_.pimpl->obexSessionMap_.end()) {
302             masInstance_.pimpl->obexSessionMap_.erase(iter);
303         }
304         if (auto iter = masInstance_.pimpl->obexIncomingMap_.find(addr);
305             iter != masInstance_.pimpl->obexIncomingMap_.end()) {
306             masInstance_.pimpl->obexIncomingMap_.erase(iter);
307         }
308         if (auto iter = masInstance_.nativeMap_.find(addr); iter != masInstance_.nativeMap_.end()) {
309             masInstance_.nativeMap_[addr]->StopTimer();
310             masInstance_.nativeMap_[addr]->IsAccepted = false;
311         }
312         if (masInstance_.stateMap_.find(addr) != masInstance_.stateMap_.end()) {
313             masInstance_.stateMap_[addr] = BTConnectState::DISCONNECTED;
314         }
315     }
316     if (masInstance_.mapObserver_) {
317         masInstance_.mapObserver_->OnTransportDisconnected(remoteAddr, masInstance_.masInstanceId_);
318     }
319 }
320 
OnDisconnect(const RawAddress & remoteAddr)321 void MapMseInstance::impl::ConnectObserver::OnDisconnect(const RawAddress &remoteAddr)
322 {
323     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
324 
325     auto addr = remoteAddr.GetAddress();
326     {
327         std::lock_guard<std::recursive_mutex> lock(masInstance_.instanceMapMutex_);
328         if (auto iter = masInstance_.pimpl->obexSessionMap_.find(addr);
329             iter != masInstance_.pimpl->obexSessionMap_.end()) {
330             masInstance_.pimpl->obexSessionMap_.erase(iter);
331         }
332         if (auto iter = masInstance_.pimpl->obexIncomingMap_.find(addr);
333             iter != masInstance_.pimpl->obexIncomingMap_.end()) {
334             masInstance_.pimpl->obexIncomingMap_.erase(iter);
335         }
336         if (auto iter = masInstance_.nativeMap_.find(addr); iter != masInstance_.nativeMap_.end()) {
337             masInstance_.nativeMap_[addr]->StopTimer();
338             masInstance_.nativeMap_[addr]->IsAccepted = false;
339         }
340         if (masInstance_.stateMap_.find(addr) != masInstance_.stateMap_.end()) {
341             masInstance_.stateMap_[addr] = BTConnectState::DISCONNECTED;
342         }
343     }
344     if (masInstance_.pimpl->content_) {
345         masInstance_.pimpl->content_->SetNotificationRegistration(remoteAddr, (int)NotificationStatus::OFF);
346     }
347 }
348 
OnBusy(const RawAddress & remoteAddr,bool isBusy)349 void MapMseInstance::impl::ConnectObserver::OnBusy(const RawAddress &remoteAddr, bool isBusy)
350 {
351     std::lock_guard<std::recursive_mutex> lock(masInstance_.instanceMapMutex_);
352     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
353     std::string address = remoteAddr.GetAddress();
354     if (masInstance_.nativeMap_[address]->IsBusy == isBusy) {
355         return;
356     }
357     masInstance_.nativeMap_[address]->IsBusy = isBusy;
358     if (masInstance_.mapObserver_) {
359         masInstance_.mapObserver_->OnBusy(remoteAddr, isBusy);
360     }
361 }
362 
GrantPermission(const RawAddress & remoteAddr,bool allow,bool save)363 void MapMseInstance::GrantPermission(const RawAddress &remoteAddr, bool allow, bool save)
364 {
365     bool notify = false;
366     {
367         std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
368         MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
369 
370         std::string address = remoteAddr.GetAddress();
371         if (pimpl->obexIncomingMap_.find(address) == pimpl->obexIncomingMap_.end()) {
372             return;
373         }
374         if (pimpl->obexIncomingMap_[address]->GetRemoteAddress().GetAddress() == remoteAddr.GetAddress()) {
375             if (allow) {
376                 nativeMap_[address]->StopTimer();
377                 pimpl->obexIncomingMap_[address]->AcceptConnection();
378                 nativeMap_[address]->IsAccepted = true;
379                 if (mapObserver_) {
380                     mapObserver_->OnTransportConnected(remoteAddr, masInstanceId_);
381                 }
382             } else {
383                 nativeMap_[address]->StopTimer();
384                 pimpl->obexIncomingMap_[address]->RejectConnection();
385                 nativeMap_[address]->IsAccepted = false;
386                 stateMap_[address] = BTConnectState::DISCONNECTED;
387                 notify = true;
388             }
389             pimpl->obexIncomingMap_.erase(address);
390         }
391     }
392     if (notify) {
393         if (mapObserver_) {
394             mapObserver_->OnConnectionStateChanged(remoteAddr, masInstanceId_, BTConnectState::DISCONNECTED);
395         }
396     }
397     BTPermissionType permission = AdapterManager::GetInstance()->GetMessagePermission(remoteAddr.GetAddress());
398     if (BTPermissionType::ACCESS_UNKNOWN == permission && save) {
399         if (allow) {
400             AdapterManager::GetInstance()->SetMessagePermission(
401                 remoteAddr.GetAddress(), BTPermissionType::ACCESS_ALLOWED);
402         } else {
403             AdapterManager::GetInstance()->SetMessagePermission(
404                 remoteAddr.GetAddress(), BTPermissionType::ACCESS_FORBIDDEN);
405         }
406     }
407 }
408 
DestroyIncomingConnect(std::string address)409 void MapMseInstance::DestroyIncomingConnect(std::string address)
410 {
411     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
412     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
413 
414     if (pimpl->obexIncomingMap_.find(address) != pimpl->obexIncomingMap_.end()) {
415         if (pimpl->obexIncomingMap_[address]->GetRemoteAddress().GetAddress() == address) {
416             nativeMap_[address]->StopTimer();
417             pimpl->obexIncomingMap_[address]->RejectConnection();
418             nativeMap_[address]->IsAccepted = false;
419             pimpl->obexIncomingMap_.erase(address);
420         }
421     }
422 }
423 
GetDatabaseIdentifier(void)424 uint64_t MapMseInstance::GetDatabaseIdentifier(void)
425 {
426     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
427 
428     return databaseIdentifier_;
429 }
430 
UpdateDatabaseIdentifier(void)431 void MapMseInstance::UpdateDatabaseIdentifier(void)
432 {
433     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
434 
435     databaseIdentifier_++;
436 }
437 
UpdateFolderVersionCounter(void)438 void MapMseInstance::UpdateFolderVersionCounter(void)
439 {
440     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
441 
442     folderVersionCounter_++;
443 }
444 
GetFolderVersionCounter(void)445 uint64_t MapMseInstance::GetFolderVersionCounter(void)
446 {
447     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
448 
449     return folderVersionCounter_;
450 }
451 
GetConversationVersionCounter(void)452 uint64_t MapMseInstance::GetConversationVersionCounter(void)
453 {
454     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
455 
456     return conversationVersionCounter_;
457 }
458 
UpdateConversationVersionCounter(void)459 void MapMseInstance::UpdateConversationVersionCounter(void)
460 {
461     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
462 
463     conversationVersionCounter_++;
464 }
465 
GetMasId(void)466 uint8_t MapMseInstance::GetMasId(void)
467 {
468     MSE_LOG_INFO("%{public}s Enter Mas id : %u", __PRETTY_FUNCTION__, masInstanceId_);
469 
470     return masInstanceId_;
471 }
472 
IsConnected(const std::string & addr)473 bool MapMseInstance::IsConnected(const std::string &addr)
474 {
475     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
476     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
477 
478     bool result = false;
479     if (addr == "") {
480         if (pimpl->obexSessionMap_.size() > 0)
481             result = true;
482     } else {
483         if (pimpl->obexSessionMap_.find(addr) != pimpl->obexSessionMap_.end())
484             result = true;
485     }
486     MSE_LOG_INFO("Is Connected result : %{public}d", result);
487     return result;
488 }
489 
GetConnectState(void)490 int MapMseInstance::GetConnectState(void)
491 {
492     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
493     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
494     uint8_t result = PROFILE_STATE_DISCONNECTED;
495     for (auto &state : stateMap_) {
496         switch (state.second) {
497             case BTConnectState::CONNECTING:
498                 result |= PROFILE_STATE_CONNECTING;
499                 break;
500             case BTConnectState::CONNECTED:
501                 result |= PROFILE_STATE_CONNECTED;
502                 break;
503             case BTConnectState::DISCONNECTING:
504                 result |= PROFILE_STATE_DISCONNECTING;
505                 break;
506             case BTConnectState::DISCONNECTED:
507                 result |= PROFILE_STATE_DISCONNECTED;
508                 break;
509             default:
510                 break;
511         }
512     }
513     MSE_LOG_INFO("Get Connect State : %{public}d", result);
514     return result;
515 }
516 
GetConnectDevices(std::list<RawAddress> & devices)517 void MapMseInstance::GetConnectDevices(std::list<RawAddress> &devices)
518 {
519     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
520     for (auto &address : pimpl->obexSessionMap_) {
521         bool has = true;
522         for (auto &device : devices) {
523             if (device.GetAddress() == address.first) {
524                 has = false;
525                 break;
526             }
527         }
528         if (auto state = stateMap_.find(address.first); state != stateMap_.end()) {
529             if (state->second != BTConnectState::CONNECTED) {
530                 has = false;
531             }
532         }
533         if (has) {
534             devices.push_back(RawAddress(address.first));
535         }
536     }
537 }
538 
GetDeviceState(const std::string & addr,int & result)539 void MapMseInstance::GetDeviceState(const std::string &addr, int &result)
540 {
541     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
542 
543     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
544     if (auto state = stateMap_.find(addr); state != stateMap_.end()) {
545         switch (state->second) {
546             case BTConnectState::CONNECTING:
547                 result = PROFILE_STATE_CONNECTING;
548                 break;
549             case BTConnectState::CONNECTED:
550                 result |= PROFILE_STATE_CONNECTED;
551                 break;
552             case BTConnectState::DISCONNECTING:
553                 result = PROFILE_STATE_DISCONNECTING;
554                 break;
555             case BTConnectState::DISCONNECTED:
556                 result |= PROFILE_STATE_DISCONNECTED;
557                 break;
558             default:
559                 break;
560         }
561     }
562 }
563 
GetDevicesByStates(std::vector<RawAddress> & devices,const std::vector<int> & states)564 void MapMseInstance::GetDevicesByStates(std::vector<RawAddress> &devices, const std::vector<int> &states)
565 {
566     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
567     for (auto &stateMap : stateMap_) {
568         for (auto &state : states) {
569             if (stateMap.second == BTConnectState(state)) {
570                 GetDevicesNative(devices, stateMap.first);
571             }
572         }
573     }
574 }
575 
GetDevicesNative(std::vector<RawAddress> & devices,const std::string & address)576 void MapMseInstance::GetDevicesNative(std::vector<RawAddress> &devices, const std::string &address)
577 {
578     bool has = true;
579     for (auto &device : devices) {
580         if (device.GetAddress() == address) {
581             has = false;
582             break;
583         }
584     }
585     if (has) {
586         devices.push_back(RawAddress(address));
587     }
588 }
DisConnect(const std::string & addr)589 void MapMseInstance::DisConnect(const std::string &addr)
590 {
591     {
592         std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
593         if (addr == "") {
594             for (auto iter = pimpl->obexSessionMap_.begin(); iter != pimpl->obexSessionMap_.end(); iter++) {
595                 if (BTConnectState::DISCONNECTING != stateMap_[addr]) {
596                     iter->second->Disconnect();
597                 }
598             }
599         }
600         if (pimpl->obexSessionMap_.find(addr) == pimpl->obexSessionMap_.end()) {
601             return;
602         }
603     }
604     if (mapObserver_) {
605         mapObserver_->OnConnectionStateChanged(RawAddress(addr), masInstanceId_, BTConnectState::DISCONNECTING);
606     }
607     {
608         std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
609         if (RET_NO_ERROR == pimpl->obexSessionMap_[addr]->Disconnect()) {
610             return;
611         }
612         MSE_LOG_INFO("Call Obex Session Disconnect error.");
613         pimpl->obexSessionMap_.erase(addr);
614     }
615     SetConnectState(addr, BTConnectState::DISCONNECTED);
616     if (mapObserver_) {
617         mapObserver_->OnConnectionStateChanged(RawAddress(addr), masInstanceId_, BTConnectState::DISCONNECTED);
618     }
619 }
620 
AcceptedNoCallBack(bool disable)621 bool MapMseInstance::AcceptedNoCallBack(bool disable)
622 {
623     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
624 
625     shutDownEnable_ = disable;
626     bool ret = false;
627     {
628         std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
629         for (auto &iter : nativeMap_) {
630             if (iter.second->IsAccepted) {
631                 ret = true;
632                 break;
633             }
634         }
635     }
636     return ret;
637 }
638 
IsBusy(const std::string & addr)639 bool MapMseInstance::IsBusy(const std::string &addr)
640 {
641     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
642 
643     if (nativeMap_.find(addr) == nativeMap_.end()) {
644         return false;
645     }
646     return nativeMap_[addr]->IsBusy;
647 }
648 
Enable(MapMseMnscli & mnsClient)649 int MapMseInstance::Enable(MapMseMnscli &mnsClient)
650 {
651     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
652 
653     shutDownEnable_ = false;
654     pimpl->content_ = std::make_unique<MapMseResource>(mnsClient, dispatcher_, *this);
655     pimpl->content_->SetRemoteFeatureMask(supportedFeatures_);
656     pimpl->mseServer_ = std::make_unique<MapMseServer>(*pimpl->content_,
657         dispatcher_,
658         *pimpl->connectObserver_,
659         *this,
660         rfcommNo_,
661         goepL2capPsm_,
662         serviceName_,
663         accountItem_,
664         smsSupport_);
665     pimpl->mseServer_->SetRemoteFeatureMask(supportedFeatures_);
666     return pimpl->mseServer_->Enable();
667 }
668 
Disable(void)669 void MapMseInstance::Disable(void)
670 {
671     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
672 
673     shutDownEnable_ = true;
674     if (pimpl->mseServer_) {
675         pimpl->mseServer_->Disable();
676     }
677 }
678 
AddServiceClassIdList(void)679 int MapMseInstance::AddServiceClassIdList(void)
680 {
681     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
682 
683     BtUuid btUuid = {BT_UUID_16, {MAS_SERVICE_CLASS_UUID}};
684     if (SDP_AddServiceClassIdList(sdpHandle_, &btUuid, MAS_SERVICE_CLASS_ID_NUMBER)) {
685         MSE_LOG_ERROR("Call SDP_AddServiceClassIdList Error");
686         return Result::FAIL;
687     }
688     return Result::SUCCEED;
689 }
690 
AddProtocolDescriptorList(void)691 int MapMseInstance::AddProtocolDescriptorList(void)
692 {
693     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
694 
695     rfcommNo_ = RFCOMM_AssignServerNum();
696     SdpProtocolDescriptor descriptor[PROTOCOL_DESCRIPTOR_NUMBER];
697     descriptor[0].parameterNumber = 0;
698     descriptor[0].protocolUuid.type = BT_UUID_16;
699     descriptor[0].protocolUuid.uuid16 = UUID_PROTOCOL_L2CAP;
700     descriptor[1].protocolUuid.type = BT_UUID_16;
701     descriptor[1].protocolUuid.uuid16 = UUID_PROTOCOL_RFCOMM;
702     descriptor[1].parameterNumber = PROTOCOL_DESCRIPTOR_PARAMETER_NUMBER;
703     descriptor[1].parameter[0].type = SDP_TYPE_UINT_8;
704     descriptor[1].parameter[0].value = rfcommNo_;
705     descriptor[0x2].protocolUuid.type = BT_UUID_16;
706     descriptor[0x2].protocolUuid.uuid16 = UUID_PROTOCOL_OBEX;
707     descriptor[0x2].parameterNumber = 0;
708 
709     if (SDP_AddProtocolDescriptorList(sdpHandle_, descriptor, PROTOCOL_DESCRIPTOR_NUMBER)) {
710         MSE_LOG_ERROR("Call SDP_AddProtocolDescriptorList Error");
711         return Result::FAIL;
712     }
713     return Result::SUCCEED;
714 }
715 
AddServiceName(void)716 int MapMseInstance::AddServiceName(void)
717 {
718     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
719 
720     serviceName_ = "MAP MAS-";
721     if (smsSupport_) {
722         serviceName_.append(SMS_MMS_NAME);
723         supportedMsgTypes_ =
724             MAP_SUPPORTED_MESSAGE_TYPE_SMS_GSM | MAP_SUPPORTED_MESSAGE_TYPE_SMS_CDMA | MAP_SUPPORTED_MESSAGE_TYPE_MMS;
725         if (accountItem_.msgType_ == MessageType::EMAIL) {
726             serviceName_.append("_");
727             serviceName_.append(EMAIL_NAME);
728             supportedMsgTypes_ |= MAP_SUPPORTED_MESSAGE_TYPE_EMAIL;
729         } else if (accountItem_.msgType_ == MessageType::IM) {
730             serviceName_.append("_");
731             serviceName_.append(IM_NAME);
732             supportedMsgTypes_ |= MAP_SUPPORTED_MESSAGE_TYPE_IM;
733         }
734     }
735 
736     if (SDP_AddServiceName(sdpHandle_, SDP_ATTRIBUTE_PRIMARY_LANGUAGE_BASE, serviceName_.data(), serviceName_.size())) {
737         MSE_LOG_ERROR("Call SDP_AddServiceName Error");
738         return Result::FAIL;
739     }
740     return Result::SUCCEED;
741 }
742 
GetProfileVersion(void)743 void MapMseInstance::GetProfileVersion(void)
744 {
745     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
746 
747     std::string version = "map14";
748     profileVersion_ = MAP_PROFILE_VERSION14;
749     supportedFeatures_ = MAP_SUPPORTED_FEATURES_V14;
750     if (AdapterConfig::GetInstance()->GetValue(SECTION_MAP_MSE_SERVICE, PROPERTY_MAP_VERSION, version)) {
751         if (version == "map12") {
752             profileVersion_ = MAP_PROFILE_VERSION12;
753             supportedFeatures_ = MAP_SUPPORTED_FEATURES_V12;
754         } else if (version == "map13") {
755             profileVersion_ = MAP_PROFILE_VERSION13;
756             supportedFeatures_ = MAP_SUPPORTED_FEATURES_V13;
757         }
758     }
759 }
760 
AddBluetoothProfileDescriptorList(void)761 int MapMseInstance::AddBluetoothProfileDescriptorList(void)
762 {
763     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
764 
765     if (SdpProfileDescriptor profileDescriptor = {
766         .profileUuid = {BT_UUID_16, {MAP_PROFILE_DESCRIPTOR_UUID}},
767         .versionNumber = profileVersion_
768         };
769         SDP_AddBluetoothProfileDescriptorList(sdpHandle_, &profileDescriptor, MAP_PROFILE_DESCRIPTOR_NUMBER)) {
770         MSE_LOG_ERROR("Call SDP_AddBluetoothProfileDescriptorList Error");
771         return Result::FAIL;
772     }
773     return Result::SUCCEED;
774 }
775 
AddAttribute(void)776 int MapMseInstance::AddAttribute(void)
777 {
778     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
779 #ifdef MAP_MSE_L2CAP_ENABLE
780     if (SDP_AddAttribute(
781         sdpHandle_, GOEP_L2CAP_PSM_ATTRIBUTE_ID, SdpDataType::SDP_TYPE_UINT_16, (uint8_t *)&goepL2capPsm_, 0x2)) {
782         MSE_LOG_ERROR("Call SDP_AddAttribute Error");
783         return Result::FAIL;
784     }
785 #endif
786     if (SDP_AddAttribute(sdpHandle_, MAS_INSTANCE_ATTRIBUTE_ID, SdpDataType::SDP_TYPE_UINT_8, &masInstanceId_, 0x1)) {
787         MSE_LOG_ERROR("Call SDP_AddAttribute Error");
788         return Result::FAIL;
789     }
790     if (SDP_AddAttribute(sdpHandle_,
791         MAP_SUPPORTED_MESSAGE_TYPE_ATTRIBUTE_ID,
792         SdpDataType::SDP_TYPE_UINT_8,
793         &supportedMsgTypes_,
794         0x1)) {
795         MSE_LOG_ERROR("Call SDP_AddAttribute Error");
796         return Result::FAIL;
797     }
798 
799     if (SDP_AddAttribute(sdpHandle_,
800         MAP_SUPPORTED_FEATURES_ATTRIBUTE_ID,
801         SdpDataType::SDP_TYPE_UINT_32,
802         (uint8_t *)&supportedFeatures_,
803         0x4)) {
804         MSE_LOG_ERROR("Call SDP_AddAttribute Error");
805         return Result::FAIL;
806     }
807     return Result::SUCCEED;
808 }
809 
AddBrowseGroupList(void)810 int MapMseInstance::AddBrowseGroupList(void)
811 {
812     if (BtUuid btUuid = {BT_UUID_16, {SDP_PUBLIC_BROWSE_GROUP_ROOT_UUID}};
813         SDP_AddBrowseGroupList(sdpHandle_, &btUuid, MAS_BROWSE_GROUP_UUID_NUMBER)) {
814         MSE_LOG_ERROR("Call SDP_AddBrowseGroupList Error");
815         return Result::FAIL;
816     }
817     return Result::SUCCEED;
818 }
819 
RegisterServiceRecord(void)820 int MapMseInstance::RegisterServiceRecord(void)
821 {
822     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
823 
824     if (SDP_RegisterServiceRecord(sdpHandle_)) {
825         MSE_LOG_ERROR("Call SDP_RegisterServiceRecord Error");
826         return Result::FAIL;
827     }
828     BTM_AddLocalL2capPsmForLogging(BTM_HCI_LOG_FILTER_MODULE_MAP, goepL2capPsm_);
829     BTM_AddLocalRfcommScnForLogging(BTM_HCI_LOG_FILTER_MODULE_MAP, rfcommNo_);
830 
831     return Result::SUCCEED;
832 }
833 
CreateMasSdpRecord(void)834 int MapMseInstance::CreateMasSdpRecord(void)
835 {
836     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
837 
838     int retVal = Result::SUCCEED;
839     sdpHandle_ = SDP_CreateServiceRecord();
840     GetProfileVersion();
841     retVal |= AddServiceClassIdList();
842     retVal |= AddProtocolDescriptorList();
843     retVal |= AddServiceName();
844     retVal |= AddBluetoothProfileDescriptorList();
845     retVal |= AddAttribute();
846     retVal |= AddBrowseGroupList();
847     retVal |= RegisterServiceRecord();
848     folderVersionCounter_ = 1;
849     databaseIdentifier_ = 1;
850     conversationVersionCounter_ = 1;
851     return retVal;
852 }
853 
DestroyMasSdpRecord(void)854 void MapMseInstance::DestroyMasSdpRecord(void)
855 {
856     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
857 
858     if (SDP_DeregisterServiceRecord(sdpHandle_)) {
859         BTM_RemoveLocalL2capPsmForLogging(BTM_HCI_LOG_FILTER_MODULE_MAP, goepL2capPsm_);
860         BTM_RemoveLocalRfcommScnChannelForLogging(BTM_HCI_LOG_FILTER_MODULE_MAP, rfcommNo_);
861         MSE_LOG_ERROR("Call SDP_DeregisterServiceRecord Error");
862         return;
863     }
864     BTM_RemoveLocalL2capPsmForLogging(BTM_HCI_LOG_FILTER_MODULE_MAP, goepL2capPsm_);
865     BTM_RemoveLocalRfcommScnChannelForLogging(BTM_HCI_LOG_FILTER_MODULE_MAP, rfcommNo_);
866     if (RFCOMM_FreeServerNum(rfcommNo_)) {
867         MSE_LOG_ERROR("Call RFCOMM_FreeServerNum Error");
868         return;
869     }
870     if (SDP_DestroyServiceRecord(sdpHandle_)) {
871         MSE_LOG_ERROR("Call SDP_DestroyServiceRecord Error");
872         return;
873     }
874 }
875 
RegistGap(void)876 int MapMseInstance::RegistGap(void)
877 {
878     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
879 
880 #ifdef MAP_MSE_L2CAP_ENABLE
881     // register for l2cap
882     GapSecChannel secChannel = {.l2capPsm = goepL2capPsm_};
883     GapServiceSecurityInfo serviceInfo = {
884         .direction = INCOMING,
885         .serviceId = GAP_Service(MAP_SERVER_ID_START + masInstanceId_),
886         .protocolId = GAP_SecMultiplexingProtocol::SEC_PROTOCOL_L2CAP,
887         .channelId = secChannel
888     };
889     if (GAPIF_RegisterServiceSecurity(nullptr,
890         &serviceInfo,
891         GAP_SEC_IN_AUTHENTICATION | GAP_SEC_IN_ENCRYPTION | GAP_SEC_OUT_AUTHENTICATION | GAP_SEC_OUT_ENCRYPTION)) {
892         MSE_LOG_INFO("Call GAP_RegisterServiceSecurity Error");
893         return Result::FAIL;
894     }
895 #else
896     GapSecChannel secChannel = {.rfcommChannel = rfcommNo_};
897     GapServiceSecurityInfo serviceInfo = {
898         .direction = INCOMING,
899         .serviceId = GAP_Service(MAP_SERVER_ID_START + masInstanceId_),
900         .protocolId = GAP_SecMultiplexingProtocol::SEC_PROTOCOL_RFCOMM,
901         .channelId = secChannel
902     };
903 #endif
904     // register for rfcomm
905     MSE_LOG_INFO("%{public}s rfcomm no %u", __PRETTY_FUNCTION__, rfcommNo_);
906     secChannel.rfcommChannel = rfcommNo_;
907     serviceInfo.channelId = secChannel;
908     serviceInfo.protocolId = GAP_SecMultiplexingProtocol::SEC_PROTOCOL_RFCOMM;
909     if (GAPIF_RegisterServiceSecurity(nullptr,
910         &serviceInfo,
911         GAP_SEC_IN_AUTHENTICATION | GAP_SEC_IN_ENCRYPTION | GAP_SEC_OUT_AUTHENTICATION | GAP_SEC_OUT_ENCRYPTION)) {
912         MSE_LOG_INFO("Call GAP_RegisterServiceSecurity Error");
913         return Result::FAIL;
914     }
915     return Result::SUCCEED;
916 }
917 
UnRegistGap(void)918 void MapMseInstance::UnRegistGap(void)
919 {
920     MSE_LOG_INFO("%{public}s Enter", __PRETTY_FUNCTION__);
921 #ifdef MAP_MSE_L2CAP_ENABLE
922     // deregister for l2cap
923     GapSecChannel secChannel = {.l2capPsm = goepL2capPsm_};
924     GapServiceSecurityInfo serviceInfo = {
925         .direction = INCOMING,
926         .serviceId = GAP_Service(MAP_SERVER_ID_START + masInstanceId_),
927         .protocolId = GAP_SecMultiplexingProtocol::SEC_PROTOCOL_L2CAP,
928         .channelId = secChannel
929     };
930     if (GAPIF_DeregisterServiceSecurity(nullptr, &serviceInfo)) {
931         MSE_LOG_INFO("Call GAP_UnregisterServiceSecurity Error");
932     }
933 #else
934     GapSecChannel secChannel = {.rfcommChannel = rfcommNo_};
935     GapServiceSecurityInfo serviceInfo = {
936         .direction = INCOMING,
937         .serviceId = GAP_Service(MAP_SERVER_ID_START + masInstanceId_),
938         .protocolId = GAP_SecMultiplexingProtocol::SEC_PROTOCOL_RFCOMM,
939         .channelId = secChannel
940     };
941 #endif
942     // deregister for rfcomm
943     secChannel.rfcommChannel = rfcommNo_;
944     serviceInfo.channelId = secChannel;
945     serviceInfo.protocolId = GAP_SecMultiplexingProtocol::SEC_PROTOCOL_RFCOMM;
946     if (GAPIF_DeregisterServiceSecurity(nullptr, &serviceInfo)) {
947         MSE_LOG_INFO("Call GAP_UnregisterServiceSecurity Error");
948     }
949 }
950 
SetConnectState(std::string address,BTConnectState state)951 void MapMseInstance::SetConnectState(std::string address, BTConnectState state)
952 {
953     std::lock_guard<std::recursive_mutex> lock(instanceMapMutex_);
954     if (stateMap_.find(address) != stateMap_.end()) {
955         stateMap_[address] = state;
956     }
957 }
958 
GetUciFullName(void)959 std::string MapAccountItem::GetUciFullName(void)
960 {
961     std::string fullUci = "";
962     if (uci_ == "" || uciPrefix_ == "")
963         return "";
964     fullUci.append(uciPrefix_);
965     fullUci.append(":");
966     fullUci.append(uci_);
967     return fullUci;
968 }
969 }  // namespace bluetooth
970 }  // namespace OHOS