1 /*
2 * Copyright (c) 2021-2023 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 "usb_service.h"
17
18 #include <cstdio>
19 #include <iostream>
20 #include <ipc_skeleton.h>
21 #include <sstream>
22 #include <string>
23 #include <unistd.h>
24
25 #include "bundle_mgr_interface.h"
26 #include "bundle_mgr_proxy.h"
27 #include "common_timer_errors.h"
28 #include "file_ex.h"
29 #include "if_system_ability_manager.h"
30 #include "iproxy_broker.h"
31 #include "iservice_registry.h"
32 #include "iusb_srv.h"
33 #include "securec.h"
34 #include "system_ability_definition.h"
35 #include "usb_common.h"
36 #include "usb_descriptor_parser.h"
37 #include "usb_errors.h"
38 #include "usb_port_manager.h"
39 #include "usb_right_manager.h"
40 #include "usbd_bulkcallback_impl.h"
41
42 using OHOS::sptr;
43 using namespace OHOS::HDI::Usb::V1_0;
44
45 namespace OHOS {
46 namespace USB {
47 namespace {
48 constexpr const char *USB_SERVICE_NAME = "UsbService";
49 constexpr int32_t COMMEVENT_REGISTER_RETRY_TIMES = 10;
50 constexpr int32_t COMMEVENT_REGISTER_WAIT_DELAY_US = 20000;
51 constexpr uint32_t CURSOR_INIT = 18;
52 constexpr int32_t DESCRIPTOR_TYPE_STRING = 3;
53 constexpr int32_t DESCRIPTOR_VALUE_START_OFFSET = 2;
54 constexpr int32_t HALF = 2;
55 constexpr int32_t BIT_SHIFT_4 = 4;
56 constexpr int32_t BIT_HIGH_4 = 0xF0;
57 constexpr int32_t BIT_LOW_4 = 0x0F;
58 constexpr int32_t SERVICE_STARTUP_MAX_TIME = 30;
59 constexpr uint32_t UNLOAD_SA_TIMER_INTERVAL = 30 * 1000;
60 } // namespace
61
62 auto g_serviceInstance = DelayedSpSingleton<UsbService>::GetInstance();
63 const bool G_REGISTER_RESULT =
64 SystemAbility::MakeAndRegisterAbility(DelayedSpSingleton<UsbService>::GetInstance().GetRefPtr());
65
UsbService()66 UsbService::UsbService() : SystemAbility(USB_SYSTEM_ABILITY_ID, true)
67 {
68 usbHostManger_ = std::make_shared<UsbHostManager>(nullptr);
69 usbRightManager_ = std::make_shared<UsbRightManager>();
70 usbPortManager_ = std::make_shared<UsbPortManager>();
71 usbDeviceManager_ = std::make_shared<UsbDeviceManager>();
72 usbd_ = IUsbInterface::Get();
73 if (usbd_ == nullptr) {
74 USB_HILOGE(MODULE_USB_SERVICE, "IUsbInterface::Get inteface failed");
75 }
76 }
~UsbService()77 UsbService::~UsbService() {}
78
SetUsbd(const sptr<IUsbInterface> & usbd)79 int32_t UsbService::SetUsbd(const sptr<IUsbInterface> &usbd)
80 {
81 if (usbd == nullptr) {
82 USB_HILOGE(MODULE_USB_SERVICE, "UsbService usbd is nullptr");
83 return UEC_SERVICE_INVALID_VALUE;
84 }
85 usbd_ = usbd;
86
87 if (usbPortManager_ == nullptr) {
88 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
89 return UEC_SERVICE_INVALID_VALUE;
90 }
91 usbPortManager_->SetUsbd(usbd);
92
93 if (usbDeviceManager_ == nullptr) {
94 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbDeviceManager_");
95 return UEC_SERVICE_INVALID_VALUE;
96 }
97 usbDeviceManager_->SetUsbd(usbd);
98 return UEC_OK;
99 }
100
SystemAbilityStatusChangeListener(sptr<UsbServiceSubscriber> usbdSubscriber)101 UsbService::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener(
102 sptr<UsbServiceSubscriber> usbdSubscriber)
103 : usbdSubscriber_(usbdSubscriber)
104 {
105 }
106
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)107 void UsbService::SystemAbilityStatusChangeListener::OnAddSystemAbility(
108 int32_t systemAbilityId, const std::string &deviceId)
109 {
110 USB_HILOGI(MODULE_USB_SERVICE, "OnAddSystemAbility ID = %{public}d", systemAbilityId);
111 }
112
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)113 void UsbService::SystemAbilityStatusChangeListener::OnRemoveSystemAbility(
114 int32_t systemAbilityId, const std::string &deviceId)
115 {
116 USB_HILOGI(MODULE_USB_SERVICE, "OnRemoveSystemAbility ID = %{public}d", systemAbilityId);
117 if (systemAbilityId == USB_SYSTEM_ABILITY_ID) {
118 sptr<IUsbInterface> usbd_ = IUsbInterface::Get();
119 if (usbd_ != nullptr) {
120 usbd_->UnbindUsbdSubscriber(usbdSubscriber_);
121 }
122 }
123 }
124
OnStart()125 void UsbService::OnStart()
126 {
127 USB_HILOGI(MODULE_USB_SERVICE, "usb_service OnStart enter");
128 if (ready_) {
129 USB_HILOGE(MODULE_USB_SERVICE, "OnStart is ready, nothing to do");
130 return;
131 }
132
133 if (!(Init())) {
134 USB_HILOGE(MODULE_USB_SERVICE, "OnStart call init fail");
135 return;
136 }
137
138 // wait for the usbd service to start and bind usb service and usbd service
139 int32_t retryTimes = 0;
140 while (retryTimes < SERVICE_STARTUP_MAX_TIME) {
141 if (InitUsbd() != 0) {
142 break;
143 }
144 sleep(1);
145 retryTimes++;
146
147 if (retryTimes == SERVICE_STARTUP_MAX_TIME) {
148 USB_HILOGE(MODULE_USB_SERVICE, "OnStart call initUsbd failed");
149 return;
150 }
151 }
152
153 if (usbPortManager_ == nullptr) {
154 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
155 return;
156 }
157
158 usbPortManager_->Init();
159 (void)usbDeviceManager_->Init();
160 (void)InitUsbRight();
161 ready_ = true;
162 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
163 sptr<ISystemAbilityStatusChange> status = new (std::nothrow) SystemAbilityStatusChangeListener(usbdSubscriber_);
164 if (samgrProxy == nullptr || status == nullptr) {
165 USB_HILOGE(MODULE_USB_SERVICE, "samgrProxy or SystemAbilityStatusChangeListener is nullptr");
166 return;
167 }
168 int32_t ret = samgrProxy->SubscribeSystemAbility(USB_SYSTEM_ABILITY_ID, status);
169 if (ret != UEC_OK) {
170 USB_HILOGE(MODULE_USB_SERVICE, "SubscribeSystemAbility failed. ret = %{public}d", ret);
171 return;
172 }
173 USB_HILOGE(MODULE_USB_SERVICE, "OnStart and add system ability success");
174 }
175
Init()176 bool UsbService::Init()
177 {
178 USB_HILOGI(MODULE_USB_SERVICE, "usb_service Init enter");
179 if (!eventRunner_) {
180 eventRunner_ = AppExecFwk::EventRunner::Create(USB_SERVICE_NAME);
181 if (eventRunner_ == nullptr) {
182 USB_HILOGE(MODULE_USB_SERVICE, "Init failed due to create EventRunner");
183 return false;
184 }
185 }
186 if (handler_ == nullptr) {
187 handler_ = std::make_shared<UsbServerEventHandler>(eventRunner_, g_serviceInstance);
188
189 if (!Publish(g_serviceInstance)) {
190 USB_HILOGE(MODULE_USB_SERVICE, "OnStart register to system ability manager failed.");
191 return false;
192 }
193 }
194 while (commEventRetryTimes_ <= COMMEVENT_REGISTER_RETRY_TIMES) {
195 if (!IsCommonEventServiceAbilityExist()) {
196 ++commEventRetryTimes_;
197 usleep(COMMEVENT_REGISTER_WAIT_DELAY_US);
198 } else {
199 commEventRetryTimes_ = 0;
200 break;
201 }
202 }
203 USB_HILOGE(MODULE_USB_SERVICE, "Init success");
204 return true;
205 }
206
InitUsbd()207 bool UsbService::InitUsbd()
208 {
209 usbdSubscriber_ = new (std::nothrow) UsbServiceSubscriber();
210 if (usbdSubscriber_ == nullptr) {
211 USB_HILOGE(MODULE_USB_SERVICE, "Init failed\n");
212 return false;
213 }
214
215 if (usbd_ == nullptr) {
216 USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::usbd_ is nullptr");
217 return false;
218 }
219 recipient_ = new UsbdDeathRecipient();
220 sptr<IRemoteObject> remote = OHOS::HDI::hdi_objcast<HDI::Usb::V1_0::IUsbInterface>(usbd_);
221 if (!remote->AddDeathRecipient(recipient_)) {
222 USB_HILOGE(MODULE_USB_SERVICE, "add DeathRecipient failed");
223 return false;
224 }
225
226 ErrCode ret = usbd_->BindUsbdSubscriber(usbdSubscriber_);
227 USB_HILOGI(MODULE_USB_SERVICE, "entry InitUsbd ret: %{public}d", ret);
228 return SUCCEEDED(ret);
229 }
230
OnStop()231 void UsbService::OnStop()
232 {
233 USB_HILOGI(MODULE_USB_SERVICE, "entry stop service %{public}d", ready_);
234 if (!ready_) {
235 return;
236 }
237 eventRunner_.reset();
238 handler_.reset();
239 ready_ = false;
240
241 if (usbd_ == nullptr) {
242 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
243 return;
244 }
245 sptr<IRemoteObject> remote = OHOS::HDI::hdi_objcast<HDI::Usb::V1_0::IUsbInterface>(usbd_);
246 remote->RemoveDeathRecipient(recipient_);
247 recipient_.clear();
248 usbd_->UnbindUsbdSubscriber(usbdSubscriber_);
249 }
250
IsCommonEventServiceAbilityExist()251 bool UsbService::IsCommonEventServiceAbilityExist()
252 {
253 sptr<ISystemAbilityManager> sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
254 if (sm == nullptr) {
255 USB_HILOGE(MODULE_USB_SERVICE,
256 "IsCommonEventServiceAbilityExist Get ISystemAbilityManager "
257 "failed, no SystemAbilityManager");
258 return false;
259 }
260 sptr<IRemoteObject> remote = sm->CheckSystemAbility(COMMON_EVENT_SERVICE_ID);
261 if (!remote) {
262 USB_HILOGE(MODULE_USB_SERVICE, "No CesServiceAbility");
263 return false;
264 }
265 return true;
266 }
267
OpenDevice(uint8_t busNum,uint8_t devAddr)268 int32_t UsbService::OpenDevice(uint8_t busNum, uint8_t devAddr)
269 {
270 std::string name = std::to_string(busNum) + "-" + std::to_string(devAddr);
271 if (!UsbService::HasRight(name)) {
272 USB_HILOGE(MODULE_USB_SERVICE, "No permission");
273 return UEC_SERVICE_PERMISSION_DENIED;
274 }
275
276 const UsbDev dev = {busNum, devAddr};
277 if (usbd_ == nullptr) {
278 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
279 return UEC_SERVICE_INVALID_VALUE;
280 }
281 int32_t ret = usbd_->OpenDevice(dev);
282 if (ret != UEC_OK) {
283 USB_HILOGE(MODULE_USB_SERVICE, "OpenDevice failed ret:%{public}d", ret);
284 }
285
286 return ret;
287 }
288
GetDeviceVidPidSerialNumber(std::string deviceName)289 std::string UsbService::GetDeviceVidPidSerialNumber(std::string deviceName)
290 {
291 std::string strDesc = "test";
292 std::lock_guard<std::mutex> guard(mutex_);
293 for (auto it = deviceVidPidMap_.begin(); it != deviceVidPidMap_.end(); ++it) {
294 USB_HILOGI(MODULE_USB_SERVICE, " it->first = %{public}s", it->first.c_str());
295 if (it->first == deviceName) {
296 strDesc = it->second;
297 break;
298 }
299 }
300 return strDesc;
301 }
302
HasRight(std::string deviceName)303 bool UsbService::HasRight(std::string deviceName)
304 {
305 USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager HasRight");
306 if (usbRightManager_ == nullptr) {
307 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
308 return false;
309 }
310
311 if (usbRightManager_->IsSystemHap()) {
312 USB_HILOGW(MODULE_USB_SERVICE, "system app, bypass: dev=%{public}s", deviceName.c_str());
313 return true;
314 }
315 std::string bundleName;
316 if (!GetBundleName(bundleName)) {
317 USB_HILOGE(MODULE_USB_SERVICE, "HasRight GetBundleName false");
318 return false;
319 }
320
321 USB_HILOGI(MODULE_USB_SERVICE, "bundle=%{public}s, device=%{public}s", bundleName.c_str(), deviceName.c_str());
322 return usbRightManager_->HasRight(GetDeviceVidPidSerialNumber(deviceName), bundleName);
323 }
324
RequestRight(std::string deviceName)325 int32_t UsbService::RequestRight(std::string deviceName)
326 {
327 USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager RequestRight");
328 if (usbRightManager_ == nullptr) {
329 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
330 return UEC_SERVICE_INNER_ERR;
331 }
332 if (usbRightManager_->IsSystemHap()) {
333 USB_HILOGW(MODULE_USB_SERVICE, "system app, bypass: dev=%{public}s", deviceName.c_str());
334 return UEC_OK;
335 }
336 std::string bundleName;
337 if (!GetBundleName(bundleName)) {
338 USB_HILOGI(MODULE_USB_SERVICE, "RequestRight GetBundleName false");
339 return UEC_SERVICE_INNER_ERR;
340 }
341
342 USB_HILOGI(MODULE_USB_SERVICE, "bundle=%{public}s, device=%{public}s", bundleName.c_str(), deviceName.c_str());
343 return usbRightManager_->RequestRight(deviceName, GetDeviceVidPidSerialNumber(deviceName), bundleName);
344 }
345
RemoveRight(std::string deviceName)346 int32_t UsbService::RemoveRight(std::string deviceName)
347 {
348 if (usbRightManager_ == nullptr) {
349 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
350 return UEC_SERVICE_INVALID_VALUE;
351 }
352
353 if (usbRightManager_->IsSystemHap()) {
354 USB_HILOGW(MODULE_USB_SERVICE, "system app, bypass: dev=%{public}s", deviceName.c_str());
355 return UEC_OK;
356 }
357
358 std::string bundleName;
359 if (!GetBundleName(bundleName)) {
360 USB_HILOGE(MODULE_USB_SERVICE, "RequestRight GetBundleName false");
361 return UEC_SERVICE_INNER_ERR;
362 }
363
364 if (!usbRightManager_->RemoveDeviceRight(GetDeviceVidPidSerialNumber(deviceName), bundleName)) {
365 USB_HILOGE(MODULE_USB_SERVICE, "RemoveDeviceRight failed");
366 return UEC_SERVICE_INNER_ERR;
367 }
368 USB_HILOGI(MODULE_USB_SERVICE, "RemoveRight done");
369 return UEC_OK;
370 }
371
GetDevices(std::vector<UsbDevice> & deviceList)372 int32_t UsbService::GetDevices(std::vector<UsbDevice> &deviceList)
373 {
374 std::map<std::string, UsbDevice *> devices;
375
376 if (usbHostManger_ == nullptr) {
377 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_");
378 return UEC_SERVICE_INVALID_VALUE;
379 }
380
381 usbHostManger_->GetDevices(devices);
382 USB_HILOGI(MODULE_USB_SERVICE, "list size %{public}zu", devices.size());
383 for (auto it = devices.begin(); it != devices.end(); ++it) {
384 if (!(usbRightManager_->IsSystemHap())) {
385 it->second->SetmSerial("");
386 }
387 deviceList.push_back(*it->second);
388 }
389 return UEC_OK;
390 }
391
GetCurrentFunctions(int32_t & functions)392 int32_t UsbService::GetCurrentFunctions(int32_t &functions)
393 {
394 if (usbRightManager_ == nullptr) {
395 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
396 return UEC_SERVICE_INVALID_VALUE;
397 }
398 if (!(usbRightManager_->IsSystemHap())) {
399 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
400 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
401 }
402 if (usbd_ == nullptr) {
403 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
404 return UEC_SERVICE_INVALID_VALUE;
405 }
406 return usbd_->GetCurrentFunctions(functions);
407 }
408
SetCurrentFunctions(int32_t functions)409 int32_t UsbService::SetCurrentFunctions(int32_t functions)
410 {
411 USB_HILOGI(MODULE_USB_SERVICE, "func = %{public}d", functions);
412 if (usbRightManager_ == nullptr) {
413 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
414 return UEC_SERVICE_INVALID_VALUE;
415 }
416
417 int32_t ret = usbRightManager_->HasSetFuncRight(functions);
418 if (ret != 0) {
419 USB_HILOGE(MODULE_USB_SERVICE, "HasSetFuncRight fail");
420 return ret;
421 }
422 if (usbDeviceManager_ == nullptr) {
423 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbDeviceManager_");
424 return UEC_SERVICE_INVALID_VALUE;
425 }
426 usbDeviceManager_->UpdateFunctions(functions);
427
428 if (usbd_ == nullptr) {
429 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
430 return UEC_SERVICE_INVALID_VALUE;
431 }
432 return usbd_->SetCurrentFunctions(functions);
433 }
434
UsbFunctionsFromString(std::string_view funcs)435 int32_t UsbService::UsbFunctionsFromString(std::string_view funcs)
436 {
437 if (usbRightManager_ == nullptr) {
438 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
439 return UEC_SERVICE_INVALID_VALUE;
440 }
441 if (!(usbRightManager_->IsSystemHap())) {
442 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
443 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
444 }
445 USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsFromString");
446 return UsbDeviceManager::ConvertFromString(funcs);
447 }
448
UsbFunctionsToString(int32_t funcs)449 std::string UsbService::UsbFunctionsToString(int32_t funcs)
450 {
451 if (usbRightManager_ == nullptr) {
452 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
453 return "";
454 }
455 if (!(usbRightManager_->IsSystemHap())) {
456 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
457 return PERMISSION_DENIED_SYSAPI;
458 }
459 USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsToString");
460 return UsbDeviceManager::ConvertToString(funcs);
461 }
462
GetPorts(std::vector<UsbPort> & ports)463 int32_t UsbService::GetPorts(std::vector<UsbPort> &ports)
464 {
465 USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getPorts");
466 if (usbRightManager_ == nullptr) {
467 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
468 return UEC_SERVICE_INVALID_VALUE;
469 }
470 if (!(usbRightManager_->IsSystemHap())) {
471 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
472 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
473 }
474 if (usbPortManager_ == nullptr) {
475 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
476 return UEC_SERVICE_INVALID_VALUE;
477 }
478 return usbPortManager_->GetPorts(ports);
479 }
480
GetSupportedModes(int32_t portId,int32_t & supportedModes)481 int32_t UsbService::GetSupportedModes(int32_t portId, int32_t &supportedModes)
482 {
483 USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getSupportedModes");
484 if (usbRightManager_ == nullptr) {
485 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
486 return UEC_SERVICE_INVALID_VALUE;
487 }
488 if (!(usbRightManager_->IsSystemHap())) {
489 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
490 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
491 }
492 if (usbPortManager_ == nullptr) {
493 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
494 return UEC_SERVICE_INVALID_VALUE;
495 }
496 return usbPortManager_->GetSupportedModes(portId, supportedModes);
497 }
498
SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole)499 int32_t UsbService::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole)
500 {
501 USB_HILOGI(MODULE_USB_SERVICE, "calling usbd getPorts");
502 if (usbRightManager_ == nullptr) {
503 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
504 return UEC_SERVICE_INVALID_VALUE;
505 }
506 if (!(usbRightManager_->IsSystemHap())) {
507 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
508 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
509 }
510 if (usbd_ == nullptr) {
511 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
512 return UEC_SERVICE_INVALID_VALUE;
513 }
514 return usbd_->SetPortRole(portId, powerRole, dataRole);
515 }
516
ClaimInterface(uint8_t busNum,uint8_t devAddr,uint8_t interface,uint8_t force)517 int32_t UsbService::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface, uint8_t force)
518 {
519 const UsbDev dev = {busNum, devAddr};
520 if (usbd_ == nullptr) {
521 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
522 return UEC_SERVICE_INVALID_VALUE;
523 }
524 return usbd_->ClaimInterface(dev, interface, force);
525 }
526
ReleaseInterface(uint8_t busNum,uint8_t devAddr,uint8_t interface)527 int32_t UsbService::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface)
528 {
529 const UsbDev dev = {busNum, devAddr};
530 if (usbd_ == nullptr) {
531 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
532 return UEC_SERVICE_INVALID_VALUE;
533 }
534 return usbd_->ReleaseInterface(dev, interface);
535 }
536
BulkTransferRead(const UsbDev & devInfo,const UsbPipe & pipe,std::vector<uint8_t> & bufferData,int32_t timeOut)537 int32_t UsbService::BulkTransferRead(
538 const UsbDev &devInfo, const UsbPipe &pipe, std::vector<uint8_t> &bufferData, int32_t timeOut)
539 {
540 if (usbd_ == nullptr) {
541 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
542 return UEC_SERVICE_INVALID_VALUE;
543 }
544 int32_t ret = usbd_->BulkTransferRead(devInfo, pipe, timeOut, bufferData);
545 if (ret != UEC_OK) {
546 USB_HILOGE(MODULE_USB_SERVICE, "BulkTransferRead error ret:%{public}d", ret);
547 }
548 return ret;
549 }
550
BulkTransferWrite(const UsbDev & dev,const UsbPipe & pipe,const std::vector<uint8_t> & bufferData,int32_t timeOut)551 int32_t UsbService::BulkTransferWrite(
552 const UsbDev &dev, const UsbPipe &pipe, const std::vector<uint8_t> &bufferData, int32_t timeOut)
553 {
554 if (usbd_ == nullptr) {
555 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
556 return UEC_SERVICE_INVALID_VALUE;
557 }
558 int32_t ret = usbd_->BulkTransferWrite(dev, pipe, timeOut, bufferData);
559 if (ret != UEC_OK) {
560 USB_HILOGE(MODULE_USB_SERVICE, "BulkTransferWrite error ret:%{public}d", ret);
561 }
562 return ret;
563 }
564
ControlTransfer(const UsbDev & dev,const UsbCtrlTransfer & ctrl,std::vector<uint8_t> & bufferData)565 int32_t UsbService::ControlTransfer(const UsbDev &dev, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &bufferData)
566 {
567 if (usbd_ == nullptr) {
568 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
569 return UEC_SERVICE_INVALID_VALUE;
570 }
571
572 int32_t ret = UEC_SERVICE_INNER_ERR;
573 if (((uint32_t)ctrl.requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT) {
574 ret = usbd_->ControlTransferWrite(dev, ctrl, bufferData);
575 if (ret != UEC_OK) {
576 USB_HILOGE(MODULE_USB_SERVICE, "ControlTransferWrite error ret:%{public}d", ret);
577 }
578 } else {
579 bufferData.clear();
580 ret = usbd_->ControlTransferRead(dev, ctrl, bufferData);
581 if (ret != UEC_OK) {
582 USB_HILOGE(MODULE_USB_SERVICE, "ControlTransferRead error ret:%{public}d", ret);
583 }
584 }
585 return ret;
586 }
587
SetActiveConfig(uint8_t busNum,uint8_t devAddr,uint8_t configIndex)588 int32_t UsbService::SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex)
589 {
590 const UsbDev dev = {busNum, devAddr};
591 if (usbd_ == nullptr) {
592 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
593 return UEC_SERVICE_INVALID_VALUE;
594 }
595 return usbd_->SetConfig(dev, configIndex);
596 }
597
GetActiveConfig(uint8_t busNum,uint8_t devAddr,uint8_t & configIndex)598 int32_t UsbService::GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex)
599 {
600 const UsbDev dev = {busNum, devAddr};
601 if (usbd_ == nullptr) {
602 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
603 return UEC_SERVICE_INVALID_VALUE;
604 }
605 return usbd_->GetConfig(dev, configIndex);
606 }
607
SetInterface(uint8_t busNum,uint8_t devAddr,uint8_t interfaceid,uint8_t altIndex)608 int32_t UsbService::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex)
609 {
610 const UsbDev dev = {busNum, devAddr};
611 if (usbd_ == nullptr) {
612 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
613 return UEC_SERVICE_INVALID_VALUE;
614 }
615 return usbd_->SetInterface(dev, interfaceid, altIndex);
616 }
617
GetRawDescriptor(uint8_t busNum,uint8_t devAddr,std::vector<uint8_t> & bufferData)618 int32_t UsbService::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, std::vector<uint8_t> &bufferData)
619 {
620 const UsbDev dev = {busNum, devAddr};
621 if (usbd_ == nullptr) {
622 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
623 return UEC_SERVICE_INVALID_VALUE;
624 }
625 int32_t ret = usbd_->GetRawDescriptor(dev, bufferData);
626 if (ret != UEC_OK) {
627 USB_HILOGE(MODULE_USB_SERVICE, "error ret:%{public}d", ret);
628 }
629 return ret;
630 }
631
GetFileDescriptor(uint8_t busNum,uint8_t devAddr,int32_t & fd)632 int32_t UsbService::GetFileDescriptor(uint8_t busNum, uint8_t devAddr, int32_t &fd)
633 {
634 const UsbDev dev = {busNum, devAddr};
635 if (usbd_ == nullptr) {
636 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
637 return UEC_SERVICE_INVALID_VALUE;
638 }
639 int32_t ret = usbd_->GetFileDescriptor(dev, fd);
640 if (ret != UEC_OK) {
641 USB_HILOGE(MODULE_USB_SERVICE, "error ret:%{public}d", ret);
642 }
643 return ret;
644 }
645
RequestQueue(const UsbDev & dev,const UsbPipe & pipe,const std::vector<uint8_t> & clientData,const std::vector<uint8_t> & bufferData)646 int32_t UsbService::RequestQueue(const UsbDev &dev, const UsbPipe &pipe, const std::vector<uint8_t> &clientData,
647 const std::vector<uint8_t> &bufferData)
648 {
649 if (usbd_ == nullptr) {
650 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
651 return UEC_SERVICE_INVALID_VALUE;
652 }
653 int32_t ret = usbd_->RequestQueue(dev, pipe, clientData, bufferData);
654 if (ret != UEC_OK) {
655 USB_HILOGE(MODULE_USB_SERVICE, "error ret:%{public}d", ret);
656 }
657 return ret;
658 }
659
RequestWait(const UsbDev & dev,int32_t timeOut,std::vector<uint8_t> & clientData,std::vector<uint8_t> & bufferData)660 int32_t UsbService::RequestWait(
661 const UsbDev &dev, int32_t timeOut, std::vector<uint8_t> &clientData, std::vector<uint8_t> &bufferData)
662 {
663 if (usbd_ == nullptr) {
664 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
665 return UEC_SERVICE_INVALID_VALUE;
666 }
667 int32_t ret = usbd_->RequestWait(dev, clientData, bufferData, timeOut);
668 if (ret != UEC_OK) {
669 USB_HILOGE(MODULE_USB_SERVICE, "error ret:%{public}d", ret);
670 }
671 return ret;
672 }
673
RequestCancel(uint8_t busNum,uint8_t devAddr,uint8_t interfaceId,uint8_t endpointId)674 int32_t UsbService::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceId, uint8_t endpointId)
675 {
676 const UsbDev dev = {busNum, devAddr};
677 const UsbPipe pipe = {interfaceId, endpointId};
678 if (usbd_ == nullptr) {
679 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
680 return UEC_SERVICE_INVALID_VALUE;
681 }
682 return usbd_->RequestCancel(dev, pipe);
683 }
684
Close(uint8_t busNum,uint8_t devAddr)685 int32_t UsbService::Close(uint8_t busNum, uint8_t devAddr)
686 {
687 const UsbDev dev = {busNum, devAddr};
688 if (usbd_ == nullptr) {
689 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
690 return UEC_SERVICE_INVALID_VALUE;
691 }
692 return usbd_->CloseDevice(dev);
693 }
694
GetDevStringValFromIdx(uint8_t busNum,uint8_t devAddr,uint8_t idx)695 std::string UsbService::GetDevStringValFromIdx(uint8_t busNum, uint8_t devAddr, uint8_t idx)
696 {
697 const UsbDev dev = {busNum, devAddr};
698 std::vector<uint8_t> strV;
699 std::string strDesc = " ";
700
701 if (idx == 0) {
702 return strDesc;
703 }
704
705 if (usbd_ == nullptr) {
706 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
707 return nullptr;
708 }
709 int32_t ret = usbd_->GetStringDescriptor(dev, idx, strV);
710 if (ret != UEC_OK) {
711 USB_HILOGE(MODULE_USB_SERVICE, "get string[%{public}hhu] failed ret:%{public}d", idx, ret);
712 return strDesc;
713 }
714 uint32_t length = strV.size();
715 if ((length < DESCRIPTOR_VALUE_START_OFFSET) || (strV[1] != DESCRIPTOR_TYPE_STRING)) {
716 USB_HILOGI(MODULE_USB_SERVICE, "type or length error, len:%{public}u", length);
717 return strDesc;
718 }
719
720 uint16_t *tbuf = new (std::nothrow) uint16_t[length + 1]();
721 if (tbuf == nullptr) {
722 USB_HILOGI(MODULE_USB_SERVICE, "new failed\n");
723 return strDesc;
724 }
725
726 for (uint32_t i = 0; i < length - DESCRIPTOR_VALUE_START_OFFSET; ++i) {
727 tbuf[i] = strV[i + DESCRIPTOR_VALUE_START_OFFSET];
728 }
729 std::wstring wstr(reinterpret_cast<wchar_t *>(tbuf), (length - DESCRIPTOR_VALUE_START_OFFSET) / HALF);
730 strDesc = std::string(wstr.begin(), wstr.end());
731 USB_HILOGI(MODULE_USB_SERVICE, "getString idx:%{public}d length:%{public}d", idx, length);
732 delete[] tbuf;
733 return strDesc;
734 }
735
BcdToString(const std::vector<uint8_t> & bcd)736 static std::string BcdToString(const std::vector<uint8_t> &bcd)
737 {
738 std::string tstr;
739 for (uint32_t i = 0; i < bcd.size(); ++i) {
740 tstr += std::to_string((bcd[i] & BIT_HIGH_4) >> BIT_SHIFT_4);
741 tstr += std::to_string((bcd[i] & BIT_LOW_4));
742 }
743 return tstr;
744 }
745
FillDevStrings(UsbDevice & dev)746 int32_t UsbService::FillDevStrings(UsbDevice &dev)
747 {
748 uint8_t busNum;
749 uint8_t devAddr;
750 uint8_t offsetValue = 8;
751
752 busNum = dev.GetBusNum();
753 devAddr = dev.GetDevAddr();
754 uint16_t bcdDevice = dev.GetbcdDevice();
755 const std::vector<uint8_t> bcdData {(bcdDevice & 0xff), ((bcdDevice >> offsetValue) & 0xff)};
756 dev.SetVersion(BcdToString(bcdData));
757 dev.SetManufacturerName(GetDevStringValFromIdx(busNum, devAddr, dev.GetiManufacturer()));
758 dev.SetProductName(GetDevStringValFromIdx(busNum, devAddr, dev.GetiProduct()));
759 dev.SetmSerial(GetDevStringValFromIdx(busNum, devAddr, dev.GetiSerialNumber()));
760 USB_HILOGI(MODULE_USB_SERVICE,
761 "iSerial:%{public}d Manufactur:%{public}s product:%{public}s "
762 "version:%{public}s",
763 dev.GetiSerialNumber(), dev.GetManufacturerName().c_str(), dev.GetProductName().c_str(),
764 dev.GetVersion().c_str());
765
766 std::vector<USBConfig> configs;
767 configs = dev.GetConfigs();
768 for (auto it = configs.begin(); it != configs.end(); ++it) {
769 it->SetName(GetDevStringValFromIdx(busNum, devAddr, it->GetiConfiguration()));
770 USB_HILOGI(MODULE_USB_SERVICE, "Config:%{public}d %{public}s", it->GetiConfiguration(), it->GetName().c_str());
771 std::vector<UsbInterface> interfaces = it->GetInterfaces();
772 for (auto itIF = interfaces.begin(); itIF != interfaces.end(); ++itIF) {
773 itIF->SetName(GetDevStringValFromIdx(busNum, devAddr, itIF->GetiInterface()));
774 USB_HILOGI(MODULE_USB_SERVICE, "interface:%{public}hhu %{public}s", itIF->GetiInterface(),
775 itIF->GetName().c_str());
776 }
777 it->SetInterfaces(interfaces);
778 }
779 dev.SetConfigs(configs);
780
781 return UEC_OK;
782 }
783
GetDeviceInfoDescriptor(const UsbDev & uDev,std::vector<uint8_t> & descriptor,UsbDevice & dev)784 int32_t UsbService::GetDeviceInfoDescriptor(const UsbDev &uDev, std::vector<uint8_t> &descriptor, UsbDevice &dev)
785 {
786 if (usbd_ == nullptr) {
787 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
788 return UEC_SERVICE_INVALID_VALUE;
789 }
790 int32_t ret = usbd_->GetRawDescriptor(uDev, descriptor);
791 if (ret != UEC_OK) {
792 usbd_->CloseDevice(uDev);
793 USB_HILOGE(MODULE_USB_SERVICE, "GetRawDescriptor failed ret=%{public}d busNum:%{public}d devAddr:%{public}d",
794 ret, uDev.busNum, uDev.devAddr);
795 return ret;
796 }
797 uint8_t *buffer = descriptor.data();
798 uint32_t length = descriptor.size();
799 if ((!buffer) || (length == 0)) {
800 USB_HILOGE(MODULE_USB_SERVICE, "GetRawDescriptor failed len=%{public}d busNum:%{public}d devAddr:%{public}d",
801 length, uDev.busNum, uDev.devAddr);
802 return UEC_SERVICE_INVALID_VALUE;
803 }
804 dev.SetBusNum(uDev.busNum);
805 dev.SetDevAddr(uDev.devAddr);
806 dev.SetName(std::to_string(uDev.busNum) + "-" + std::to_string(uDev.devAddr));
807
808 ret = UsbDescriptorParser::ParseDeviceDescriptor(buffer, length, dev);
809 if (ret != UEC_OK) {
810 usbd_->CloseDevice(uDev);
811 USB_HILOGE(MODULE_USB_SERVICE, "ParseDeviceDescriptor failed ret=%{public}d", ret);
812 return ret;
813 }
814 return ret;
815 }
816
GetConfigDescriptor(UsbDevice & dev,std::vector<uint8_t> & descriptor)817 int32_t UsbService::GetConfigDescriptor(UsbDevice &dev, std::vector<uint8_t> &descriptor)
818 {
819 std::vector<USBConfig> configs;
820 uint8_t *buffer = descriptor.data();
821 uint32_t length = descriptor.size();
822 uint32_t cursor = CURSOR_INIT;
823 int32_t ret = UEC_OK;
824 for (uint8_t i = 0; i < dev.GetDescConfigCount(); ++i) {
825 if (length <= cursor) {
826 USB_HILOGE(MODULE_USB_SERVICE, "GetConfigDescriptor[%{public}d] length=%{public}d", i, length);
827 break;
828 }
829 USB_HILOGI(MODULE_USB_SERVICE, "GetConfigDescriptor length=%{public}d", length);
830 uint32_t configCursor = 0;
831 USBConfig config;
832 ret = UsbDescriptorParser::ParseConfigDescriptor(buffer + cursor, length - cursor, configCursor, config);
833 if (ret != UEC_OK) {
834 USB_HILOGE(MODULE_USB_SERVICE, "ParseConfigDescriptor failed ret=%{public}d", ret);
835 return ret;
836 }
837 cursor += configCursor;
838 configs.push_back(config);
839 }
840 dev.SetConfigs(configs);
841 ret = FillDevStrings(dev);
842 USB_HILOGI(MODULE_USB_SERVICE, "FillDevStrings ret=%{public}d", ret);
843 return ret;
844 }
845
GetDeviceInfo(uint8_t busNum,uint8_t devAddr,UsbDevice & dev)846 int32_t UsbService::GetDeviceInfo(uint8_t busNum, uint8_t devAddr, UsbDevice &dev)
847 {
848 USB_HILOGI(MODULE_USB_SERVICE, "busNum:%{public}d devAddr:%{public}d", busNum, devAddr);
849 const UsbDev uDev = {busNum, devAddr};
850 std::vector<uint8_t> descriptor;
851
852 if (usbd_ == nullptr) {
853 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
854 return UEC_SERVICE_INVALID_VALUE;
855 }
856 int32_t ret = usbd_->OpenDevice(uDev);
857 if (ret != UEC_OK) {
858 USB_HILOGE(MODULE_USB_SERVICE, "OpenDevice failed ret=%{public}d", ret);
859 return ret;
860 }
861
862 ret = GetDeviceInfoDescriptor(uDev, descriptor, dev);
863 if (ret != UEC_OK) {
864 USB_HILOGE(MODULE_USB_SERVICE, "GetDeviceInfoDescriptor ret=%{public}d", ret);
865 }
866 ret = GetConfigDescriptor(dev, descriptor);
867 if (ret != UEC_OK) {
868 USB_HILOGE(MODULE_USB_SERVICE, "GetConfigDescriptor ret=%{public}d", ret);
869 return ret;
870 }
871
872 usbd_->CloseDevice(uDev);
873 USB_HILOGI(MODULE_USB_SERVICE, "CloseDevice=%{public}s", dev.ToString().c_str());
874
875 return UEC_OK;
876 }
877
AddDevice(uint8_t busNum,uint8_t devAddr)878 bool UsbService::AddDevice(uint8_t busNum, uint8_t devAddr)
879 {
880 UsbDevice *devInfo = new (std::nothrow) UsbDevice();
881 if (devInfo == nullptr) {
882 USB_HILOGE(MODULE_USB_SERVICE, "new failed");
883 return false;
884 }
885
886 errno_t retSafe = memset_s(devInfo, sizeof(UsbDevice), 0, sizeof(UsbDevice));
887 if (retSafe != EOK) {
888 USB_HILOGI(MODULE_USB_SERVICE, "memset_s failed");
889 return false;
890 }
891
892 int32_t ret = GetDeviceInfo(busNum, devAddr, *devInfo);
893 USB_HILOGI(MODULE_USB_SERVICE, "GetDeviceInfo ret=%{public}d", ret);
894 if (ret != UEC_OK) {
895 delete devInfo;
896 return false;
897 }
898
899 std::string name = std::to_string(busNum) + "-" + std::to_string(devAddr);
900 std::string uniqueName = std::to_string(devInfo->GetVendorId()) + "-" + std::to_string(devInfo->GetProductId()) +
901 "-" + devInfo->GetmSerial();
902 USB_HILOGI(MODULE_USB_SERVICE, "map+: %{public}s", name.c_str());
903 {
904 std::lock_guard<std::mutex> guard(mutex_);
905 deviceVidPidMap_.insert(std::pair<std::string, std::string>(name, uniqueName));
906 }
907
908 if (usbHostManger_ == nullptr) {
909 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_");
910 return false;
911 }
912
913 usbHostManger_->AddDevice(devInfo);
914 return true;
915 }
916
DelDevice(uint8_t busNum,uint8_t devAddr)917 bool UsbService::DelDevice(uint8_t busNum, uint8_t devAddr)
918 {
919 USB_HILOGI(MODULE_USBD, "entry");
920 int32_t ret = Close(busNum, devAddr);
921 if (ret != UEC_OK) {
922 USB_HILOGE(MODULE_USBD, "Close device failed width ret = %{public}d", ret);
923 }
924
925 if (usbHostManger_ == nullptr || usbRightManager_ == nullptr) {
926 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_ or usbRightManager_");
927 return false;
928 }
929
930 std::string name = std::to_string(busNum) + "-" + std::to_string(devAddr);
931 if (!usbRightManager_->RemoveDeviceAllRight(GetDeviceVidPidSerialNumber(name))) {
932 USB_HILOGW(MODULE_USB_SERVICE, "remove right failed: %{public}s", name.c_str());
933 }
934
935 {
936 std::lock_guard<std::mutex> guard(mutex_);
937 for (auto it = deviceVidPidMap_.begin(); it != deviceVidPidMap_.end(); ++it) {
938 if (it->first == name) {
939 deviceVidPidMap_.erase(it);
940 break;
941 }
942 }
943 }
944
945 return usbHostManger_->DelDevice(busNum, devAddr);
946 }
947
InitUsbRight()948 int32_t UsbService::InitUsbRight()
949 {
950 int32_t ret = usbRightManager_->Init();
951 if (ret != UEC_OK) {
952 USB_HILOGE(MODULE_USBD, "Init usb right manager failed: %{public}d", ret);
953 return ret;
954 }
955 std::vector<std::string> devices;
956 for (auto it = deviceVidPidMap_.begin(); it != deviceVidPidMap_.end(); ++it) {
957 devices.push_back(it->second);
958 }
959 USB_HILOGI(MODULE_USBD, "clean: %{public}zu/%{public}zu", devices.size(), deviceVidPidMap_.size());
960 ret = usbRightManager_->CleanUpRightExpired(devices);
961 if (ret != USB_RIGHT_OK) {
962 USB_HILOGE(MODULE_USBD, "clean expired usb right failed: %{public}d", ret);
963 }
964 return ret;
965 }
966
UpdateUsbPort(int32_t portId,int32_t powerRole,int32_t dataRole,int32_t mode)967 void UsbService::UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode)
968 {
969 if (usbPortManager_ == nullptr) {
970 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
971 return;
972 }
973
974 usbPortManager_->UpdatePort(portId, powerRole, dataRole, mode);
975 }
976
UpdateDeviceState(int32_t status)977 void UsbService::UpdateDeviceState(int32_t status)
978 {
979 if (usbDeviceManager_ == nullptr) {
980 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbDeviceManager_");
981 return;
982 }
983
984 usbDeviceManager_->HandleEvent(status);
985 }
986
GetBundleName(std::string & bundleName)987 bool UsbService::GetBundleName(std::string &bundleName)
988 {
989 #ifdef USB_RIGHT_TEST
990 bundleName = "com.usb.right";
991 return true;
992 #endif
993 pid_t uid = GetCallingUid();
994 sptr<ISystemAbilityManager> systemAbilityManager =
995 SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
996 if (systemAbilityManager == nullptr) {
997 return false;
998 }
999 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1000 if (remoteObject == nullptr) {
1001 return false;
1002 }
1003
1004 sptr<AppExecFwk::IBundleMgr> bundleMgr(new AppExecFwk::BundleMgrProxy(remoteObject));
1005 if (bundleMgr == nullptr) {
1006 return false;
1007 }
1008
1009 ErrCode ret = bundleMgr->GetNameForUid(uid, bundleName);
1010 if (ret != ERR_OK) {
1011 USB_HILOGE(MODULE_USB_SERVICE, "failed to obtain bundleName");
1012 return false;
1013 }
1014 return true;
1015 }
1016
RegBulkCallback(const UsbDev & devInfo,const UsbPipe & pipe,const sptr<IRemoteObject> & cb)1017 int32_t UsbService::RegBulkCallback(const UsbDev &devInfo, const UsbPipe &pipe, const sptr<IRemoteObject> &cb)
1018 {
1019 if (cb == nullptr) {
1020 USB_HILOGE(MODULE_USB_SERVICE, "cb is nullptr");
1021 return UEC_SERVICE_INVALID_VALUE;
1022 }
1023 if (hdiCb_ == nullptr) {
1024 hdiCb_ = new UsbdBulkCallbackImpl(cb);
1025 }
1026 if (usbd_ == nullptr) {
1027 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
1028 return UEC_SERVICE_INVALID_VALUE;
1029 }
1030
1031 int32_t ret = usbd_->RegBulkCallback(devInfo, pipe, hdiCb_);
1032 if (ret != UEC_OK) {
1033 USB_HILOGE(MODULE_USB_SERVICE, "RegBulkCallback error ret:%{public}d", ret);
1034 }
1035 return ret;
1036 }
1037
UnRegBulkCallback(const UsbDev & devInfo,const UsbPipe & pipe)1038 int32_t UsbService::UnRegBulkCallback(const UsbDev &devInfo, const UsbPipe &pipe)
1039 {
1040 if (usbd_ == nullptr) {
1041 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
1042 return UEC_SERVICE_INVALID_VALUE;
1043 }
1044
1045 hdiCb_ = nullptr;
1046 int32_t ret = usbd_->UnRegBulkCallback(devInfo, pipe);
1047 if (ret != UEC_OK) {
1048 USB_HILOGE(MODULE_USB_SERVICE, "UnRegBulkCallback error ret:%{public}d", ret);
1049 }
1050 return ret;
1051 }
1052
BulkRead(const UsbDev & devInfo,const UsbPipe & pipe,sptr<Ashmem> & ashmem)1053 int32_t UsbService::BulkRead(const UsbDev &devInfo, const UsbPipe &pipe, sptr<Ashmem> &ashmem)
1054 {
1055 if (ashmem == nullptr) {
1056 USB_HILOGE(MODULE_USB_SERVICE, "BulkRead error ashmem");
1057 return UEC_SERVICE_INVALID_VALUE;
1058 }
1059
1060 if (usbd_ == nullptr) {
1061 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
1062 return UEC_SERVICE_INVALID_VALUE;
1063 }
1064 int32_t ret = usbd_->BulkRead(devInfo, pipe, ashmem);
1065 if (ret != UEC_OK) {
1066 USB_HILOGE(MODULE_USB_SERVICE, "BulkRead error ret:%{public}d", ret);
1067 }
1068 return ret;
1069 }
1070
BulkWrite(const UsbDev & devInfo,const UsbPipe & pipe,sptr<Ashmem> & ashmem)1071 int32_t UsbService::BulkWrite(const UsbDev &devInfo, const UsbPipe &pipe, sptr<Ashmem> &ashmem)
1072 {
1073 if (ashmem == nullptr) {
1074 USB_HILOGE(MODULE_USB_SERVICE, "BulkWrite error ashmem");
1075 return UEC_SERVICE_INVALID_VALUE;
1076 }
1077
1078 if (usbd_ == nullptr) {
1079 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
1080 return UEC_SERVICE_INVALID_VALUE;
1081 }
1082 int32_t ret = usbd_->BulkWrite(devInfo, pipe, ashmem);
1083 if (ret != UEC_OK) {
1084 USB_HILOGE(MODULE_USB_SERVICE, "BulkWrite error ret:%{public}d", ret);
1085 }
1086 return ret;
1087 }
1088
BulkCancel(const UsbDev & devInfo,const UsbPipe & pipe)1089 int32_t UsbService::BulkCancel(const UsbDev &devInfo, const UsbPipe &pipe)
1090 {
1091 if (usbd_ == nullptr) {
1092 USB_HILOGE(MODULE_USB_SERVICE, "UsbService::usbd_ is nullptr");
1093 return UEC_SERVICE_INVALID_VALUE;
1094 }
1095 int32_t ret = usbd_->BulkCancel(devInfo, pipe);
1096 if (ret != UEC_OK) {
1097 USB_HILOGE(MODULE_USB_SERVICE, "BulkCancel error ret:%{public}d", ret);
1098 }
1099 return ret;
1100 }
1101
AddRight(const std::string & bundleName,const std::string & deviceName)1102 int32_t UsbService::AddRight(const std::string &bundleName, const std::string &deviceName)
1103 {
1104 USB_HILOGI(MODULE_USB_SERVICE, "calling AddRight");
1105 if (usbRightManager_ == nullptr) {
1106 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
1107 return UEC_SERVICE_INVALID_VALUE;
1108 }
1109 if (!(usbRightManager_->IsSystemHap())) {
1110 USB_HILOGW(MODULE_USB_SERVICE, "is not system app");
1111 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
1112 }
1113 USB_HILOGI(MODULE_USB_SERVICE, "AddRight bundleName = %{public}s, deviceName = %{public}s", bundleName.c_str(),
1114 deviceName.c_str());
1115 if (!usbRightManager_->AddDeviceRight(GetDeviceVidPidSerialNumber(deviceName), bundleName)) {
1116 USB_HILOGE(MODULE_USB_SERVICE, "AddDeviceRight failed");
1117 return UEC_SERVICE_INNER_ERR;
1118 }
1119 USB_HILOGI(MODULE_USB_SERVICE, "AddRight done");
1120 return UEC_OK;
1121 }
1122
Dump(int fd,const std::vector<std::u16string> & args)1123 int UsbService::Dump(int fd, const std::vector<std::u16string> &args)
1124 {
1125 if (fd < 0) {
1126 USB_HILOGE(MODULE_USB_SERVICE, "fd is invalid fd:%{public}d", fd);
1127 return UEC_SERVICE_INVALID_VALUE;
1128 }
1129
1130 std::vector<std::string> argList;
1131 std::transform(args.begin(), args.end(), std::back_inserter(argList), [](const std::u16string &arg) {
1132 return Str16ToStr8(arg);
1133 });
1134
1135 if (argList.empty()) {
1136 USB_HILOGE(MODULE_USB_SERVICE, "argList is empty");
1137 DumpHelp(fd);
1138 return UEC_SERVICE_INVALID_VALUE;
1139 }
1140
1141 if (argList[0] == USB_HOST) {
1142 usbHostManger_->Dump(fd, argList[1]);
1143 } else if (argList[0] == USB_DEVICE) {
1144 usbDeviceManager_->Dump(fd, argList);
1145 } else if (argList[0] == USB_PORT) {
1146 usbPortManager_->Dump(fd, argList);
1147 } else if (argList[0] == USB_HELP) {
1148 DumpHelp(fd);
1149 } else {
1150 dprintf(fd, "Usb Dump service:invalid parameter.\n");
1151 DumpHelp(fd);
1152 }
1153 return UEC_OK;
1154 }
1155
DumpHelp(int32_t fd)1156 void UsbService::DumpHelp(int32_t fd)
1157 {
1158 dprintf(fd, "Refer to the following usage:\n");
1159 dprintf(fd, "-h: dump help\n");
1160 dprintf(fd, "============= dump the all device ==============\n");
1161 dprintf(fd, "usb_host -a: dump the all device list info\n");
1162 dprintf(fd, "------------------------------------------------\n");
1163 usbDeviceManager_->GetDumpHelp(fd);
1164 usbPortManager_->GetDumpHelp(fd);
1165 }
1166
UnLoadSelf(UnLoadSaType type)1167 void UsbService::UnLoadSelf(UnLoadSaType type)
1168 {
1169 auto task = []() {
1170 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1171 if (samgrProxy == nullptr) {
1172 USB_HILOGE(MODULE_USB_SERVICE, "get samgr failed");
1173 return;
1174 }
1175
1176 auto ret = samgrProxy->UnloadSystemAbility(USB_SYSTEM_ABILITY_ID);
1177 if (ret != UEC_OK) {
1178 USB_HILOGE(MODULE_USB_SERVICE, "unload failed");
1179 }
1180 };
1181
1182 if (type == UNLOAD_SA_IMMEDIATELY) {
1183 task();
1184 return;
1185 }
1186
1187 if (usbHostManger_ == nullptr || usbDeviceManager_ == nullptr) {
1188 USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_ or usbDeviceManager_");
1189 return;
1190 }
1191
1192 unloadSelfTimer_.Unregister(unloadSelfTimerId_);
1193 unloadSelfTimer_.Shutdown();
1194
1195 std::map<std::string, UsbDevice *> devices;
1196 usbHostManger_->GetDevices(devices);
1197 if (devices.size() != 0 || usbDeviceManager_->IsGadgetConnected()) { // delay unload conditions
1198 USB_HILOGW(MODULE_USB_SERVICE, "not need unload");
1199 return;
1200 }
1201
1202 if (auto ret = unloadSelfTimer_.Setup(); ret != Utils::TIMER_ERR_OK) {
1203 USB_HILOGE(MODULE_USB_SERVICE, "set up timer failed %{public}u", ret);
1204 return;
1205 }
1206 unloadSelfTimerId_ = unloadSelfTimer_.Register(task, UNLOAD_SA_TIMER_INTERVAL, true);
1207 }
1208
OnRemoteDied(const wptr<IRemoteObject> & object)1209 void UsbService::UsbdDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
1210 {
1211 auto pms = DelayedSpSingleton<UsbService>::GetInstance();
1212 if (pms == nullptr) {
1213 USB_HILOGE(MODULE_USB_SERVICE, "failed to GetInstance");
1214 return;
1215 }
1216 pms->UnLoadSelf(UNLOAD_SA_IMMEDIATELY);
1217 }
1218 } // namespace USB
1219 } // namespace OHOS
1220